Javascript Interview Preparation Cheatsheet
SCOPE, SINGLE THREAD , CALL STACK,AND HOISTING
In this article , you will get a small cheatsheet that helps in your interview preparation and the topics are SCOPE, SINGLE THREAD , CALL STACK,AND HOISTING.
SCOPE IN JAVASCRIPT
If a variable or expression is declared within an scope is access by that scope only but when a variable or expression is declared in global scope is accessed by other scopes.
Scopes are arranged in layered in a hierarchy, that the child scope accesses variable or expression from there parent scope but not vice versa.
TYPES OF SCOPE
- Global Scope
- Local scope
- Function Scope
- Block Scope
Global Scope
The default scope used by the javascript is the global scope and the variables and expression is access by other scope. In the context of browser, they are found on window object.
var a= 2;
function num(){
console.log(a);
}
Here, the variable
'a'
is access by any type of scope within this global scope.
Local scope
The variable which is bound between a scope and it is not a global scope.
var a= 2;
function num(){
if(a>1){
var b=3;
console.log(b);
}
}
Here, the variable
'b'
is access only in local scope that is if function.
Function Scope
The variable declared within a function can only access by only that function.
var a= 2;
function num(){
var b=3;
console.log(b);
}
Here, the variable
'b'
is access only in function scope that is num function.
Block Scope
The newest form of scope, the variable declared within a { }
cannot accessed outside of it.
{
var b=3;
console.log(b);
}
Here, the variable
'b'
is access only in { } .
Single Thread
Javascript is a Synchronous Single threaded language. The single thread is define as within the call stack, your JS code is read and gets executed line by line, the execution takes place one by one execution that is the execution is done one at a time.
Call Stack
- Call stack is as like the stack of data structure.
- There is a global execution context inside the call stack and it will execute the line by line code then the statement carrying by the call stack inside it one by one and when the execution is done then it will pop out from the call stack .
- If the function call's another function inside that function then it will push in the stack and after execution it will be pop out.
- After execution of all statement the stack become empty, i.es., the global execution context is also pop out from the call stack.
Hoisting
A variable can be used before it has been declared that is accessing something before it is declared.
console.log(name);
sum();
var name = "jyoti";
function sum() {
console.log("hello sum")
}
console.log(a)
var a = 10;
console.log(a)
// console.log(b) //Cannot access 'b' before initialization
let b = 20;
console.log(b)
// console.log(c) //Cannot access 'c' before initialization
const c = 20;
console.log(c)