JavaScript Interview Preparation CheatSheet

JavaScript Interview Preparation CheatSheet

Get to know all about Scope, Single threaded JS, Call Stack, and Hoisting.

ยท

5 min read

What is Scope?

The Scope is like a home for values and expressions in which it can be referenced.

Type of scope in JavaScript:

  • Block Scope
  • Local Scope
  • Global Scope
  • Lexical Scope

1. Block Scope

Variables declared using keywords *let* and *const* and that too inside the curly brackets i.e. {}, are having Block Scope. Block Scope is not valid for the keyword *var*.

Example 1:

{
    let _name = "Danial";    
}
    console.log(_name);       // This is not valid, the name can't access here

Example 2:

{
    var _name = "Danial";
}
    console.log(_name);        // This is valid, name can access here

2. Local Scope

If a variable resides or is declared inside the function, then the home or scope of that variable is within that particular function. This is valid for all three keywords i.e., *let*, *const*, and *var*. A lifetime of local variables is within the function.

Example:

function fruit() {
         let _name = "apple";              // local scope
}
console.log(_name);                       // Reference Error: name is not defined
function fruit() {
         var _name = "apple";            // local scope
}
console.log(_name);                      // Reference Error: name is not defined
function fruit() {
         const _name = "apple";        // local scope
}
console.log(_name);                      // Reference Error: name is not defined

3. Global Scope

If a variable resides or is declared outside the function, it's known as a Global variable. In this case, the home or scope of a global variable is the whole program. The variable can be declared with any of the keywords i.e., let, var, and const when making it global.

Example:

var _name = "kiwi";                  // Global scope
function fruit() {
   _name = "apple";                  // You can also change the value of a global variable 
   console.log(_name);
}
fruit();                             // Output: apple

4. Lexical Scope

The behavior of the local variables which can access all the variables from their parent scope are having the Lexical scope.

Example:

var x = 10;                 

var lexScope = function() {
    var y = 20;
    console.log(`The value of x and y is accesable inside lexScope ${x} & ${y}`);

    function innerFunc() {
        var z = x * y;
        console.log(`The value of z is ${x} * ${y} = ${z}`);
    }

    innerFunc();

}

lexScope();
console.log(`the value of x is ${x}`);                // The global variable`x` is accesible here
// console.log(`the value of y is ${y}`);            // Reference error: y is not defined
// console.log(`the value of z is ${z}`);            // Reference error: y is not defined

In the above example, Inside the lexScope function, the variable x is accessible as it is the global variable and can further get accessible due to its global behavior. Moving ahead, Inside the innerFunc, you'll see that the variables x and y are accessible here! This is due to the Lexical behavior with their parent's Scope.

With this example, we've seen that all the values starting from the global variable x and then the variable y, then local variable z is accessible when innerFunc gets invoked.

Since y and z are local variables, we can't access these values outside the function.

Is JavaScript a Single Threaded language?๐Ÿค”

Yes, JavaScript is a Single threaded language which means it has only one call stack for the execution of the JS program. Since it's the Single threaded language means it's Synchronous in nature. By Synchronous it means that the execution of a program is done line by line irrespective of how much time it takes to execute a line of code i.e., When the first line of code is found, it'll move to the call stack and executed and then finds next line of code and goes to the call stack and goes same.

Call Stack

As we know that within JavaScript there is execution context, memory heap, lexical environment, and much more for the execution of JS code but there is also one important thing which is the Call Stack. Call stack is the same as we've seen in stack data structure means it follows the same principle which is FILO(First In Last Out). Let's understand the behavior of the call stack:

Whenever the JS code runs, it creates the execution context which is known as the Global execution context. Then, this Global execution is the first one to move on to the stack and will be the last one to move out. Whenever A Function is invoked, it acts as another Small program and creates its own Execution Context and moves to the stack, and after execution, it will also move out from the stack, and again the control goes back to the global execution context. In a nutshell, Call Stack maintains the order of execution Contexts. It CREATES Execution Context whenever a Program starts or a Function is invoked and it pops out the Execution Context when a Function or Program ENDS.

var x = 10;
var sum = function(y) {
    var z = x + y;
    console.log(z);
}
var result = sum(20);                    // function invoking

callstack.png

In the above example, when JS code starts to run, the global execution goes inside the stack, then the function sum() also goes in in the form of the Execution context. At last, when the function sum() gets invoked, it's execution context goes out from the stack and left only the global execution context which also moves out when the whole code gets run completely.

Hoisting

Unlike other programming languages, JavaScript provides the leverage of using the variables and functions even before its declaration, and this phenomenon in JavaScript is known as Hoisting.

Let's First see the Function Hoisting Example:

randnum(30);        // function invoked

function randnum(num) {
    console.log(num);
}

In the above example, we are easily able to use the function even before its declaration, this is the merit of Hoisting.

Now let's see the Variable Hoisting Example:

console.log(b);          // prints undefined, but not giving the error
var b = 20;
console.log(a);          // ReferenceError: Cannot access 'a' before initialization
let a = 10;
console.log(c);          // ReferenceError: Cannot access 'c' before initialization
const c = "aiman";

In the above example of Variable Hoisting, you see that using the keyword var, it prints undefined and not giving the error. While using let and const, the same error is coming.

Thanks for the valuable time to read this blog :)

ย