JavaScript Interview Preparation Cheatsheet

JavaScript Interview Preparation Cheatsheet

Scope

The scope can be termed as limitations and availability on how values and expressions can be referred to or accessed.

If variable or expression is not in the current scope, they won't be available to use.

Scopes are Layered in Hierarchy

  • Child Scope has access to the Parent Scope.
  • the Parent Scope doesn't have access to the Child Scope.

Let's understand this with the help of some code.

scopeExample.png

Now that we know, how the scope chain works, let's dive into the Type of Scopes.

1.) Global Scope:

This is the Default Scope for all the codes there running. The variables or expressions in this scope can be accessed anywhere in the program.

2.) Module Scope:

Codes that are running in the module can be termed as module scope.

3.) Function Scope:

Scope created inside or within a function is termed function scope. Example: a variable declared inside a function cannot be accessed outside the same function.

function examplefn(){
  const x = " inside fn declared variable";
  console.log(x);   // is valid 
}
console.log(x);   // is not valid. Gives Error

4.) Block Scope:

These scopes are created with a pair of curly braces or blocks. Example: variables declared with let or const cannot be accessed outside the scope they are defined in. Note: variable declared with var can be accessed outside the scope.

{
  var x = "something accessible";
}
console.log(x);

___________________________________

{
  const y = "Not accessible outside brackets"; 
}
console.log(y);   // Gives Reference Error: *y is not defined*

Single Threaded

Thread: is the execution of running multiple tasks/programs at the same time. i.e.,

Each unit is capable of executing code -- called Thread

JS is Single Threaded which means only 1 statement is executed at a time.

  • if any function is called, the program execution waits until that function completes execution.
  • then it continues to the next line of code.

Example: calling a friend over the phone till he responds.

const calling = () => {
  const ringing = () => {
    console.log('Hello There');
    ... // other statements if any
    ...
  }
  ringing();
}

calling function resized.png

Did you find this article valuable?

Support Gautam Nath by becoming a sponsor. Any amount is appreciated!