JavaScript Interview CheatSheet

·

6 min read

JavaScript Interview CheatSheet

Scope

Scope in JavaScript refers to the current context of code, which determines the accessibility of variables to JavaScript.

In other words we can say that Scope is determine where variables function and objects are accessible in code during runtime.

types of scope in JS :

  • Local Scope
  • Global Scope
  • Lexical Scope

1. Local Scope

Variables that can be used in a specific part of the code are considered to be in a local scope. And these variables are called Local Variables. There are two types of local scope in JavaScript,

  • Block Scope
  • Function Scope

1.1 Block Scope

Block scope is an area within conditions (if or switch) or loops (for and while) or whenever you see {} it is a block. In a block, you can declare variables using const and let keywords. These variables exist only within the corresponding block.

if (false) {
   const msg = 'Hello World';
   console.log(msg); // 'Hello World'
}
console.log(msg); // ReferenceError

The first console.log(msg) works because the variable is declared inside the if block, therefore the msg is accessed from the scope where it is defined.

The second console.log(msg) throws a reference error because the variable is accessed outside of its scope.

The code blocks of if, for, while, and standalone also delimit a scope.

Keyword var is not block scoped

1.2 Function Scope

When you declare a variable in a function, that variable is only visible within the function.

function call() {
   var msg = 'Make a call';
   console.log(msg);
}
call(); // 'Make a call'
console.log(msg); // Error: msg is not defined

call() function body creates a scope. The variable msg is only accessible within the function scope and if we try to access it outside of its scope then it'll throw an error.

2. Global Scope

The global scope is the outermost scope and the variables can be accessed from any inner(Local) scope.

var msg = 'Hello World';
function readMsg() {
   console.log(msg);
}
readMsg(); // 'Hello World'

Variables declared inside the global scope are named Global Variables, these variables can be accessed from any scope.

3. Lexical Scope

When a function is defined inside another function, the inner function can access the variables of the outer function. This operation is called Lexical scoping.

function outerFunc() {
   var msg = 'Hello World';

   function innerFunc() {
      console.log(msg);
   }

   innerFunc();
}
outerFunc(); // 'Hello World'

The inner function is lexically bound to the execution context of its outer function.

Call Stack

A call stack is a mechanism for an interpreter (like the JavaScript interpreter in a web browser) to keep track of its place in a script that calls multiple functions — what function is currently being run and what functions are called from within that function, etc.

  • 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.

function f1() {
  console.log("Hi From f1!");
}

function f2() {
  f1();
  console.log("Hi From f2");
}

f2();

//Output
//
//Hi from f1
//Hi from f2

Step 1: When the code loads in memory, the global execution context gets pushed in the stack.

Step 2: The f2() function gets called, and the execution context of f2() gets pushed into the stack.

Step 3: The execution of f2() starts and during its execution, the f1() function gets called inside the f2() function. This causes the execution context of f1() to get pushed in the call stack.

Step 4: Now the f1() function starts executing. A new stack frame of the console.log() method will be pushed to the stack.

Step 5: When the console.log() method runs, it will print “Hi from f1” and then it will be popped from the stack. The execution context go will back to the function and now there not any line of code that remains in the f1() function, as a result, it will also be popped from the call stack.

Step 6: This will similarly happen with the console.log() method that prints the line “Hi from f2” and then finally the function f2() would finish and would be pushed off the stack.

synchronous and single thread

Javascript is a synchronous language by default. This means that all the statements and functions execute one after the other in a predefined order. Javascript behaves this way because it has only a single thread of execution.

Thread in computer science is the execution of running multiple tasks or programs at the same time. Each unit capable of executing code is called a thread.

Single-Threaded JavaScript is known to be single-threaded because of its property of having only one call stack, which some other programming languages have multiple. JavaScript functions are executed on the call stack, by LIFO (Last In First Out).

Hoisting

JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code.

Hoisting allows functions to be safely used in code before they are declared.

Variable and class declarations are also hoisted, so they too can be referenced before they are declared. Note that doing so can lead to unexpected errors, and is not generally recommended.

Function hoisting

One of the advantages of hoisting is that it lets you use a function before you declare it in your code.

catName("Tiger");

function catName(name) {
  console.log(`My cat's name is ${name}`);
}
/*
The result of the code above is: "My cat's name is Tiger"
*/

var hoisting

Here we declare and then initialize the value of a var after using it. The default initialization of the var is undefined.var hoisting

Here we declare and then initialize the value of a var after using it. The default initialization of the var is undefined.

console.log(num); // Returns 'undefined' from hoisted var declaration (not 6)
var num; // Declaration
num = 6; // Initialization
console.log(num); // Returns 6 after the line with initialization is executed.

let and const hoisting

Variables declared with let and const are also hoisted but, unlike var, are not initialized with a default value. An exception will be thrown if a variable declared with let or const is read before it is initialized.

console.log(num); // Throws ReferenceError exception as the variable value is uninitialized
let num = 6; // Initialization

Did you find this article valuable?

Support Shailraj by becoming a sponsor. Any amount is appreciated!