After facing many interviews for the position of the JavaScript developer, I gathered the following most asked JavaScript interview questions from all of the interviews. Here I will list out all the questions and their answers with explanations. All of these questions are based on my personal interview experiences. I hope it will also help you to crack your interviews.
Hoisting is the default nature of JavaScript in which declarations of the variables go on the top. That means if we are using a variable on the top of our code but it is declared on the bottom, then the JS engine will not give any error. For example:
console.log(a);
//some code
//some code
//some code
var a = 1;
The output of the code will be “undefined”. That means it will not show any error because the declaration of variable “a” went on the top. One most important thing to remember is that let
and const
don’t support the hoisting. Only variables declared with keyword var
support hoisting.
let
and const
were introduced in ES6. Differentiate var
vs let
vs const
?Before the introduction of let
and const
, there was only var
. It had some constraints because of its functional scope. But after the introduction of let
and const
, which both have block scope, those constraints were removed. That’s why they were introduced. Let’s explain their difference:
const
const
, initialization is necessary.
let
let
.
var
var
has a functional scope by default.var
.So these are the main 4 differences of var
, let
and const
.
This question is also related to the hoisting and scope of variables. It is related to let
and const
. If we want to initialize a variable but it is not declared yet, it is declared in the code below. Then it will give a reference error and that is called a temporal dead zone. In this zone, the variable is dead temporarily. For example:
a = 4; // here JavaScript engine will give a reference error
// some code
// some code
let a;
In the above code, the zone between variable initialization and declaration is called Temporal Dead Zone.
const a = []; //empty array assigned to static variable a
const b = []; //empty array assigned to static variable b
console.log(a === b);
console.log(a == b);
Output:
false
false
This is because the memory allocation to both of the empty arrays (a and b) is different. In the case of an array, JavaScript doesn’t match the values, but it matches the references (memory locations). This is the reason why the output is false in both cases.
setTimeout(() => {
console.log('1');
}, 0);
console.log('2');
setTimeout(() => {
console.log('3');
}, 100);
Promise.resolve().then(() => {
console.log('4');
});
Ans.
2
4
1
3
The reason behind this output is the task queue for the JavaScript runtime. The meaning of 0 millisecond in setTimeout()
doesn’t mean that callbacks will be executed after 0 milliseconds.
It depends on the total waiting tasks. So the value “2” will be consoled first, then Promise
and then the setTimeout()
’s callbacks will run.
let x = 10;
function a() {
let x = 20;
b();
}
function b() {
console.log(x);
}
a();
10
Yes, the answer will be 10. Here we are calling the a()
. Which is executing the b()
. This b()
is consoling the value of x which is 10 because it is getting the global value of x. In b()
, there is one another x is defined but its scope is only inside the block. That’s why in b()
the global value of x will be taken.
for(var j = 0; j <=2; j++){ setTimeout(()=>{
console.log(j);
},100)
}
Ans.
3
3
3
This output is due to the ***functional scope of ***var
. If we use let
here instead of var
, the output will be:
0
1
2
This is because, in the case of var
, the complete loop runs 3 times before setTimeout()
calls the callback. So when setTimeout()
runs the callback it gets the value of i=3
every time because var
has the scope all over the function. Hence it prints the value 3, three times.
But in the case of let
, every time there will be a new value of let
due to its block scope. Hence, it prints the output as 0,1,2. This is also a reason why let
and const
were introduced in ES6. Prior to ES6, such tasks were resolved with the help of Closures.
With the help of closure, we can make a global variable => local or private. In other words, you can say that closures are the ability of a function to remember the variables (or functions) declared in the outer scope.
So closures give the ability to a function to remember the outside variables even after the execution of the function. Let us explain with an example.
function closureExample() {
var count = 1;
function checkValue() {
console.log(count);
}
count++;
return checkValue;
}
var counter = closureExample();
counter(); // result will be 2
So in the above example, you can see that value of the outer variable count
is available to the inner function checkValue()
even after the execution of the outer function. All is this due to closure.
IIFE (pronounced as iffee) means Immediately Invoked Function Expression. This is a function expression that is executed as soon as it is created. That means we don’t need to call it after creation, it will be executed by default. The syntax is:
(function(){
// some code
// some code
// some code
})();
Or with an arrow function
(()=>{
// some code
// some code
// some code
})();
Main use cases of IIFE:
setTimeout()
in a for loop, then they may give us unexpected results. To solve such issues we enclosed the timer functions in IIFE.
Arrow functions were introduced in ES6 and are different from the regular functions in many ways, let us discuss:
1. Different Syntax:
Yes, the first visual difference is their syntax, which is of course different.
Regular function:
function example() {
//some code
}
Arrow function:
const example = () => {
//some code
}
Here we created example()
in both cases and can see the different syntax for both.
2. Implicit Return
Regular functions:
In the case of a regular function, if we want to return from a single statement, the syntax will be:
function example(value) {
return value + 1;
}
So, this is the most common return case we use in JavaScript. But in the case of the Arrow function, it is different.
Arrow function:
In this case, the syntax will be:
const example = (value) => value +1;
Here we omitted the curly braces and it automatically returned the value without a return
statement.
3. Constructors
Regular functions:
Regular functions can be used as a constructor. For example:
function Example(param) {
this.param = param;
}
const ins = new Example('one');
console.log(ins instanceof Example)
In the above example, the console.log will be true.
Arrow functions:
In the case of arrow functions, we can’t use the new keyword to create an instance. In this case, JavaScript will show an error.
4. Behavior of this
this
is also known as the execution context. Its behavior is different for both the regular and arrow functions.
Arrow functions don’t have their own this
but in the case of regular functions they have their own this
. The following example will clear everything:
let obj = {
name: "Ankit",
arrowFunction:() => {
console.log("Hello " + this.name); // this won’t work here
},
regularFunction(){
console.log("Hi " + this.name); // this will work here
}
};
obj.arrowFunction();
obj.regularFunction();
Output:
Hello undefined
Hi Ankit
So in the case of the arrow function, there is no this
and output of this.name
is undefined
but in the case of regular function output is Ankit
.
These are the most asked JavaScript interview questions and answers for experienced as well as for fresher candidates.
If you have any doubts, or suggestions, or want to correct something in the article, please comment below. Also, if you want more such content, please let me know and I will provide QAs along with suitable programming examples. Thank you and all the best for the interview.
I’m a full-stack developer working in an MNC named eClerx. My main skills are ReactJS, Angular and NodeJS.
Also published here.