Today we will discuss some important topics to crack JavaScript interviews.
Scopes in JavaScript.
1. Global and Local Scope
Here we will take a real life example of a House
Global Scope
- Any variable declared outside of a function is considered to be in global scope
- It can be accessed and modified from anywhere in your code.
Local Scope
- Variables initialized and declared inside a function are in the local scope of the function.
- Variables inside that function will have different scope for every call of that function.
- Function Scope and Block Scope are type of Local Scope.
Suppose in your house Kitchen or your Bedroom are in the Global scope. But the things inside Kitchen and Bedroom are Local scope. You can access Kitchen or Bedroom in the house. But if you want to get an apple from Fridge you have to get into the Kitchen or if you want to take rest you have to go to the Bedroom to access the Bed. So here Fridge is the Local scope variable in Kitchen like wise Bed is the local scope variable in Bedroom.
var house = "access hallway"; // Global Scope
function kitchen() {
var fridge = "get an apple"; // Local Scope
console.log(fridge);
}
function bedroom() {
var bed = "getting some rest"; // Local Scope
console.log(bed);
}
test1();
test2();
console.log(name);
2. Function Scope
- When a variable is declared inside a function, the variable is said to be function scoped.
- The declared variable is accessible from anywhere inside the function, but not outside the function.
- If you try to access the variable from outside of the function it will throw a reference error.
- Variable defined with
let
andconst
in a function will behave in the same way they do in block scope.
function functionScope() {
var var1 = 'A function or local scoped Variable';
return var1;
}
console.log(functionScope());
// Output -> A function or local scoped Variable
console.log(var1);
// Output -> ReferenceError: var1 is not defined
3. Block Scope
- A block is a piece of code written inside a pair of curly braces.
- Conditional statements and loops are both examples of a block.
- Block scope means that every time a block is created so is a new local scope.
- Variables declared with
let
andconst
are not accessible outside the block scope. But variable declared withvar
are accessible outside the block scope as variable declared withlet
andconst
are blocked scope but variable declared withvar
are function scope.
function blockScope() {
if(true) {
var x = 'Variable declared with var';
let y = 'Variable declared with let or const';
console.log('INSIDE block', x);
// Output -> INSIDE block Variable declared with var
console.log('INSIDE block', y);
// Output -> INSIDE block Variable declared with let or const
}
console.log('OUTISDE block', x);
// Output -> OUTSIDE block Variable declared with var
console.log('OUTISDE block', y);
// Output -> ReferenceError: y is not defined
}
blockScope();
JavaScript is a Single-threaded Language
- JavaScript is a interpreted Language. It means the JS code is converted to machine code at the runtime
- There are several types of interpreters such as Chrome's V8 engine, Safari's Webkit engine or Firefox's Quantum engine. The most popular browser engine used is Chrome's V8 Engine which is also used in popular backend JavaScript backend environment Nodejs.
- Each engine contains a call stack, memory heap, message queue, event loop, etc.
- Here single threaded means the single thread contains single heap memory and a single call stack and this single thread is the only thread responsible for the execution of code and the code is executed line by line(one line of code at a time) with the help of heap memory, call stack, event loop and message queue.
Hoisting
In JavaScript, Hoisting is the process in which interpreter moves the declaration of function, variable, classes at the top of the scope before starting the execution of the code. NOTE- Only the declaration is moved to the scope of scope not the assignment, assignment are done at same place.
Hoisting allows use or reference of functions, variable or classes before even they are decaled.
- Best practice is to declare functions, variables and function before execution or
use strict
mode which force you to declare variable at the top of the scope.
Function Hoisting
- Functions declarations are allowed to use before declaration because of hoisting. Not the same case when functions are declared using expressions.
hoisting();
function hoisting() {
console.log('Calling Function before declaration');
}
// Output ->
// Calling Function before declaration
Variable Hoisting
- Hoisting works with variables too. You can access variable before declaration.
- However JavaScript Engine only hoist declaration not assignment even if the variable is initialized and declared at the same line.
var
Hoisting
- The default initialization of the var is undefined.
console.log(one);
console.log(two);
var one = 'ONE';
var two;
two = 'TWO';
// Output ->
// undefined
// undefined
let
and const
hoisting
- Hoisted also works with variables declared with
let
andconst
but, unlikevar
, are not initialized with a default value. So if accessing it before declaration result into Reference error.
console.log(one);
const one = 'ONE';
// Output ->
// ReferenceError: Cannot access 'one' before initialization
Call Stack
- Call Stack is a stack of functions in the order they are executed in the execution of JavaScript code.
- The function called first is at the last position in the stack.
- Like stack, call stack also functions in LIFO fashion i.e. Last In First Out.
- At the start of the execution of any JavaScript code a Global Execution Context is added/pushed in the Call Stack
- For every new function call a new Execution Context is added/pushed inside the call stack at the top of Global Execution Context and when the function is executed it is then removed from the call stack.
- If a function is called it is added at the top of the stack but if the function call also contains another function then a new execution context is added at the top of the stack for another function call.
- When the execution of all the lines of JavaScript is finished the Global Execution Context is also removed/popped out from the call stack.
- We Will understand Call Stack with the help of an example below.
Example
- In the below example there there are three functions -
one()
,two()
andthree()
. - First we call function
one()
. Functionone()
calls functiontwo()
which in turn calls functionthree()
. - As soon as we call function
one()
a new execution context is added/pushed to the call stack and execution of functionone()
starts line by line. - As function
one()
calls functiontwo()
a new execution context of functiontwo()
is added/pushed to the call stack and now the execution of functiontwo()
will start line by line. - Same for the function
three()
when called from functiontwo()
a new execution context is added for functionthree()
and now the execution of functionthree()
will start line by line. - As soon as the function
three()
is executed it is removed/popped out from the top of call stack and the remaining line of code of the functiontwo()
will be executed. And as soon as the execution of functiontwo()
is finished it is removed/popped out from the top of call stack and the remaining line of code of the functionone()
will be executed. And when the functionone()
is also finished executing then it is also removed/popped out from the call stack.
If you like this blog please drop a comment or share with your friends!!!