Javascript  Interview Cheat Sheet

Javascript Interview Cheat Sheet

Learning about Scope, Single thread in jS , Call Stack and Hoisting

ยท

6 min read

What is Scope?

A scope is a current execution area in which values and expressions are "visible" or can be referenced.

A scope is a current execution area in which values and expressions are "visible" or can be referenced.

JavaScript has the following kinds of scopes:

  • Global scope: The default scope for all code running in script mode.
  • Module scope: The scope for code running in module mode.
  • Function scope: The scope is created with a function.

ES6 introduced two important new JavaScript keywords: let and const.

These two keywords provide Block Scope in JavaScript.

  • Block scope: The scope is created with a pair of curly braces (a block).

Screenshot 2022-09-10 at 5.37.05 PM.png

Global Scope

A variable declared at the top of a program or outside of a function is considered a global scope variable.

A global variable has Global Scope: All scripts and functions on a web page can access it.

Example

let myName = "Rishabh Thakur"; //  Declared in Global Scope

function myDetails() {
  let myAge = 21;
  console.log(`Hi, My name is ${myName} and my age is ${myAge}`); // WE can access myName inside function scope also 
}

myDetails();
console.log(myName);

As we can see that myName is declared in the global space which is why we are able to access it anywhere inside the code.

Warning: Do NOT create global variables unless you intend to. Your global variables (or functions) can overwrite window variables (or functions). Any function, including the window object, can overwrite your global variables and functions.

Local/Function Scope

A variable can also have a local scope, i.e it can only be accessed within a function.A function creates a scope, so that (for example) a variable defined exclusively within the function cannot be accessed from outside the function or within other functions. For instance, the following is invalid:

Example

let myName = "Rishabh Thakur"; //  Declared in Global Scope

function myDetails() {
  let myAge = 21; Declared in Local Scope
  console.log(`Hi, My name is ${myName} and my age is ${myAge}`); 
}

myDetails();
console.log(myAge); // This will give you an error .

console.log(myAge); ReferenceError: myAge is not defined

Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.

Local variables are created when a function starts and deleted when the function is completed. Variables declared with var, let and const are quite similar when declared inside a function.

Block Scope

Blocks only scope let and const declarations, but not var declarations.

{
  var myName = "Rishabh Thakur";
}
console.log(myName); // Rishabh Thakur

We can access myName because it is var. (To know more about let , const and var refer this article .

{
  let myName = "Rishabh Thakur";
}
console.log(myName); // ReferenceError: myName is not defined

You will get an error because let is having a blocked scope.

Javascript (Synchronous Single threaded language )

If you have been using Javascript for a while then you may come across the phrase that itโ€™s a single-threaded language.

What does that mean?

Javascript engine runs on a browser engine (V8, SpiderMonkey, etc) that has a memory heap and a call stack.

JS is single-threaded which means only one statement is executed at a time.

But before that let me explain to you a little more terminologies:

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.

let myDetail = () => {
  let myName = "Rishabh Thakur";
  const showDetails = () => {
    console.log(`My name is ${myName}`);
  };
  showDetails();
};
myDetail();

So, what happens under the call stack?

Screenshot 2022-09-11 at 12.45.34 PM.png

The call stack job is to fill in the instructions and pop an instruction as it gets executed. Javascript is a single-threaded language that can be non-blocking. Single-threaded means it has only one call stack. Whatever is on the top of the call stack is run first. In the above program, functions are run sequentially.

The JavaScript engine maintains a stack data structure called function execution stack. The purpose of the stack is to track the current function in execution.

  • When the JavaScript engine invokes a function, it adds it to the stack, and the execution starts.
  • If the currently executed function calls another function, the engine adds the second function to the stack and starts executing it.
  • Once it finishes executing the second function, the engine takes it out from the stack.
  • The control goes back to resume the execution of the first function from the point it left it last time.
  • Once the execution of the first function is over, the engine takes it out of the stack.
  • Continues unit the stack is empty.

Hoisting in Javascript

JavaScript hoisting refers to a mechanism in which functions, variables, and classes are available throughout the program, even before they are declared. The javascript 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.

Hoisting in variables

Hoisting works with variables too, so you can use a variable in code before it is declared and/or initialized.

However, JavaScript only hoists declarations, not initializations! This means that initialization doesn't happen until the associated line of code is executed, even if the variable was originally initialized then declared, or declared and initialized in the same line.

Below are some examples showing what can happen if you use a variable before it is declared.

var Hositing

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

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

The same thing happens if we declare and initialize the variable in the same line.

console.log(name); // Returns 'undefined' from hoisted var declaration 
var name= "Rishabh Thakur";  // Declaration and Initialization
console.log(name); // 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(name); // Throws ReferenceError exception as the variable value is uninitialized
let name= "Rishabh Thakur";// Declaration and Initialization

console.log(name); // Returns 6 after the line with initialization is executed.

Hoisting in Functions

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

myDetails();

function myDetails() {
  let myName = "Rishabh Thakur";
  let myAge = 21;
  console.log(`My name is ${myName} and my age is ${myAge}`);
}

myDetails();

With function hoisting, it doesn't matter where in the code a function is declared, it can be used the same way anywhere in the program and it works perfectly.

So, I hope now are able to understand some of the main topics of the interview, if you find it useful please like and comment on it and follow me on hashnode for more such awesome content.

Thank You ๐Ÿ˜Š

ย