JavaScript interview cheat Sheet.

JavaScript interview cheat Sheet.

Learn about the types javascript scopes, function scope, nested scope, lexical scope, local scope, global scope and single thread

JavaScript Scope

Scope defines where variables can be accessed or referenced. In Javascript there are three types of Scopes. Global can be accessed from anywhere within a program, other variables may only be available in their specific block.

javascript scope.png

Let's understand scope with a real life example spoose we are living in a same city. The city is our global scope. The temperature in our city today is 45 degrees celcius, and everyone feels very hot, but in my home it is only 24 degrees celcius because I have an AC. Only those people who live inside my house/block are able to access this facility, which is called local scope. hope i am able to teach you scope with real life example.

Block Scope :- Before ES6 (2015), javaScript had only Global Scope and Function Scope.

ES6 (2015) introduce the two important new javaScript keywords : let and const these two keywords provide the block scope in javaScript.

What is block scope in javaScript? Block Level Scope: The block scope restricts the variable that is declared inside a function & specific block, from access by the outside of the block. The let & const keyword facilitates the variables to be block scoped.

Note:- Variables declared with the var keyword can NOT have block scope it can be accessed from outside the block.

A code block in JavaScript defines a scope for variables declared using let and const:

if (true) {
  // "if" block scope
  const message = 'Hello';
  console.log(message); // 'Hello'
}
console.log(message); // throws ReferenceError

The first console.log(message) is correctly logs the variable becasue it's calling to own if block scope it's give us a output "Hello"

But in second console.log(message) throws ReferenceError because it's calling a variable outside from the variable block scope. Using let,const every variable inside {}"carly braces" create block scope outside the {} we cannot access the variable.

In the following example for loop defines a scope:

for (const color of ['white', 'red', 'blue']) {
  // "for of" block scope
  const message = 'Hi';
  console.log(color);   // 'white', 'red', 'blue'
  console.log(message); // 'Hi', 'Hi', 'Hi'
}
console.log(color);   // throws ReferenceError
console.log(message); // throws ReferenceError

outside the block accessing variable color,message throw us ReferenceError but inside for block it logs values.

var keyword is not block scoped keyword As we declare a variable using const and let keyword in our previous section, the code creates a block scope for variable but using var keyword it's not create a block scope let's see how it's work using an example :-

if (true) {
  // "if" block scope
  var message = 'Hello';
  console.log(message); // 'Hello'
}
console.log(message); // 'Hello'

Declaring using var keyword message variable, as expected is accessable with in the block scope, and also accessable outside the if block. A code block like if, for, while etc. doesn't create a scope for var keyword but function does.

Example:-

function add() {
    var myAdd = 1+1;
}
console.log(add());
console.log(myAdd);

Declaring var keyword inside code block doesn't create a block scope for var variable but function create a function scope for var keyword. we cannot access the var variable declared inside a function to outside function scope.

Funtion scope :-

A function in javascript provide us a scope for variables declared using var, let, const.

Let create an function using var keyword:-

function run() {
  // "run" function scope
  var message = 'Run';
  console.log(message); // 'Run'
}
run();
console.log(message); // throws ReferenceError

Run() function body create a function scope. The variable message accessable inside the run function scope but variable message doesn't accessable outside the function scope. it's called a function scope.

**Nested scope:-

** An good part of scopes is that scope can be nested

In the following example the function run() create a scope, and inside the run function if condition code block create an block scope.

function nested() {
    // "run" function scope
    const message = 'function scope';
    if (true) {
      // "if" code block scope
      const friend = 'Bubba';
      console.log(message); // 'function scope'   // able to access function scope variable inside another block
    }
    console.log(friend); // throws ReferenceError // doesn't able to access outside the block scope
  }
  nested();

We are able to access message variable inside the inner block scope but we cannot access friend variable declared inside innner block from outside the inner block. for an example child can access parent variable but parent cannot access child variables.

**Lexical Scope :-

** Lexical scope, also known as Static Scope. This is the process of determining the scope of a variable during the compile time is called lexical scoping and the scope we get is called lexical scope. Declare a inner function inside a function and access parent variables in inner function it's called lexical scope. Let's define 2 functions, having the function innerFunc() is nested inside outerFunc().

function outerFunc() {
    // the outer scope
    let outerVar = 'I am from outside!';
    function innerFunc() {
      // the inner scope
      console.log(outerVar); // 'I am from outside!'
       }
    innerFunc();
  }
  outerFunc();

Global scope :-

The global scope is outer scope. it's accessable from any inner scope(block scope, function scope, lexical ) <script> tag is a global scope in javascript.

<script src="style.js"></script>
//global scope
let number = 5;

Declaring a variable inside the global content is named global variable. global variable accessable from any scope inside the global content. in above example number variable is the global variable it can accessed from any scope like block scope, function etc.

The global scope is a mechanism that lets the host of JavaScript (browser, Node) supply applications with host-specific functions as global variables.

window and document, for example, are global variables supplied by the browser.

Single Thread

Scope (1).png

JavaScript is a single-threaded language it is synchronous in nature. JS code is read and gets executed line by line. Single threaded means it has only one call stack. Stacks follow the FILO method (First in Last out) whenever a line of code gets inside the call stack it gets executed and move out of the stack.

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. We use call stack for memorizing which function is running right now. The call stack works based on the LIFO principle i.e., last-in-first-out.

Also, the JavaScript engine uses a call stack to manage execution contexts:

Global execution context function execution contexts

When you execute a script, the JavaScript engine creates a global execution context and pushes it on top of the call stack.

function add(a, b) {
    return a + b;
}

function average(a, b) {
    return add(a, b) / 2;
}

let x = average(10, 20);

When A function called it will popup into the call stack once the function executed then it will pop out from the stack

let's see with an image example:-

stackcall.png

Hoisting

In javaScript hoisting is the behavior of JavaScript in the declaration of functions, variables, or classes. Hoisting allows functions to be safely used in code before they are declared. JavaScript allocates memory for all variables and functions defined in the program before execution.

// Hoisting : Accessing Something before it is declared
console.log(number);
var number = 40;

In the above example we can see we are calling variable before declaration and it will throw an error Accessing Something before it is declared.

sum() //Hello world
function sum() {
  console.log("Hello world");
}

But using functions we are able to access it before declaration it's called hoisting.