JavaScript Interview cheatsheet - Understand Scope, Hoisting, Thread and Call stack
In this article, we will cover 4 important JavaScript interview topics that might be asked in your next interview.
- Scope
- Hoisting
- Single & Multi thread
- Call stack
1. Scope
The accessibility or visibility of variables in a JavaScript program is known as scope. In other words, a variable can be declared at any point in a program. But access to these variables are limited and made available depending upon the scope, as explained below.
Global Scope
The global scope includes any variable that is not contained within a function or block (a pair of curly braces). Global scope variables can be accessed from anywhere in the program. An example showing the global scope of a variable is given below.
var hello = 'Hello';
function sayHello() {
console.log(hello);
}
// 'Hello' gets logged
sayHello();
Local or Function Scope
Variables declared inside a function are local variables. They can only be accessed from within that function; they are not accessible from outside code. An example showing local scope of a variable is given below.
function sayHello() {
var hello = 'Hello';
console.log(hello);
}
// 'Hello' gets logged
sayHello();
console.log(hello); // Uncaught ReferenceError: hello is not defined
Block Scope
Block scope is the accessibility of a variable within a pair of curly braces { }
. But not that, variables declared with var
keyword within a block, have global scope. Only variables declared with let
and const
keywords have block scope.
{
let hello = 'Hello';
var pet= 'Tiger';
console.log(hello); // 'Hello' gets logged
}
console.log(language); // 'Tiger' gets logged
console.log(hello); // Uncaught ReferenceError: hello is not defined
2. JavaScript Hoisting
Prior to executing the code, the interpreter appears to relocate the declarations of functions, variables, and classes to the top of their scope using a process known as Hoisting in JavaScript. Functions can be securely utilized in code before they have been declared.
Variable and class also can be declared and are hoisted, allowing them to be referenced prior to declaration. It should be noted that, this can result in issues like values being taken from other scopes and is not recommended. There are two types of hoisting, as listed below.
Function Hoisting
Function hoisting allows you to use a function before declaring it in your code as shown in the below example. Without function hoisting, we would have to first write down the function display and only then can we call it. Also if function hoisting is not done by JavaScript, we would have got an error.
sayWord("Hello");
function sayWord(inputString) {
console.log(inputString); // 'Hello' gets logged
}
Variable Hoisting
Variable can also be hoisted, and JavaScript hoists only declarations made with var
keyword, and not initializations. Even if the variable was initially initialised then defined, or declared and initialised on the same line, initialization does not occur until the associated line of code is run. The variable has its default initialization as undefined
, until that point in the execution is reached. Variables declared using let
or const
keywords are not hoisted and will return a reference error.
console.log(x) // 'undefined' is logged from hoisted var declaration (instead of 7)
var x // Declaration of variable x
x = 7; // Initialization of variable x to a value 7
console.log(x); // 7 is logged post the line with initialization's execution.
3. Single Thread
A thread in computer science is the execution of running multiple tasks or programs at the same time. A single-thread language is one with a single call stack and a single memory heap. It means that it runs only one thing at a time. Thread is like a process which executes the program, line by line in a sequential fashion. By default, the browser uses a single thread to run all the JavaScript in your page, as well as to perform layout, reflows, and garbage collection. This means that long-running JavaScript functions can block the thread, leading to an unresponsive page and a bad user experience.
Also JavaScript is a single threaded language non-blocking language, which means that if some function is getting blocked, it skips to the next line. This is why JavaScript is also called as a synchronous language. Synchronous (or sync) execution usually refers to code executing in sequence. In sync programming, the program is executed line by line, one line at a time. Each time a function is called, the program execution waits until that function returns before continuing to the next line of code.
- A stack is a continuous region of memory, allocating local context for each executed function.
- A heap is a much larger region, storing everything allocated dynamically.
- A call stack is a data structure which basically records where we are in the program.
4. Call Stack
Call stack is used by JavaScript to keep track of multiple function calls. It is basically like the popular data structure 'stack' where data can be pushed and popped and follows the Last In First Out (LIFO) principle.
When a script calls a function, the interpreter adds it to the call stack and then starts carrying out the function. Any functions that are called by that function are added to the call stack further up, and run where their calls are reached. When the current function is finished, the interpreter takes it off the stack and resumes execution where it left off in the last code listing. If the stack takes up more space than it had assigned to it, it results in a "stack overflow" error.
As you can see, the functions are added to the stack, executed and later deleted. It's the so-called LIFO way - Last In, First Out. Each entry in the call stack is called a stack frame.