Today We will cover the most four important topics asked in JavaScript interview question. They are
Scope
Hoisting
Call-Stack
Thread
let's dive into the topics.
Scope
The scope is the current context of execution in which variable and function are store. If a variable or function is not in the current scope, it will not be available for use.
There are three types of scope in JavaScript:
- Global Scope
- Local Scope
- Block Scope
Global Scope
From where everyone get access to get the values or can call the function is Global Scope.
var a = "World";
function hello() {
console.log("Hello " + a); // Hello World
}
hello();
Local Scope
From where anyone get access to get the values Local Scope.
function hello() {
var a = 10
console.log.(a) // 10
}
hello()
console.log(a) // not defined
Block Scope
when we declare a variable inside any block means inside curly braces {}
with let
and const
it is call Block Scope.
Scope Chain
It simply refers to probability of get any values of a variable.
var a = 10;
function a() {
var a = 20;
function b() {
var a = 30;
console.log(a); // 30
}
b();
console.log(a); // 20
}
a();
console.log(a); // 10
Here we can see in b()
it prints the value as 30 because it gets the value from its nearest possible scope.
We can try to understand via store. Suppose I need a pen. So go to my nearest shop to buy this pen if I get the I will buy the pen. If I don't get the pen I go further distance shop and vice versa...
Hoisting
JavaScript Hoisting refers to the process where a variable or a function or a class placed. Because of Hoisting, we can get any variable's value or call function before it is declare.
hello();
console.log(a); // undefined
function hello() {
console.log("Hello"); // Hello
}
var a = 10;
Call stack
A call stack is a mechanism where any JavaScript operation executed.
Execution context has two phases:
- Memory allocation
- Code execution
Memory allocation
In first phase it scans every variable and assign undefined and take the reference of function () {...}
Code execution
In this phase it executes the code.
function a() {
console.log("Hello -- a");
function b() {
console.log("Hello -- b");
}
b();
}
a();
console.log("Hello -- Global execution");
Single Thread
Thread in computer science is the execution of running multiple tasks or programs at the same time. Single thread means it will execute a line of code at a time.
JavaScript is by default a Synchronous Single Threaded language. It can do one line code execute at a time. There are seen some Asynchronous type programme in JavaScript like setTimeOut()
. Actually, when JavaScript sees this type of code it doesn't execute this immediately. It jumps to next line of code. It finishes all Synchronous code then come back to them and execute them.
function a() {
function b() {
setTimeOut(() => {
console.log("Hello -- b");
}, 3000);
}
b();
}
a();
console.log("Hello -- Global execution");
Output
Hello -- Global execution
Hello -- b