JavaScript as we all know is a very powerful programming language and is used widely for web development. This is the reason why companies want to hire top-notch JavaScript developers. This article is written with the sole purpose of getting you through these interviews and landing your dream job. This article showcases a total of 30 most asked JavaScript questions which will also clear all your JavaScript fundamentals.
Table of Contents
Javascript Interview Questions for Freshers
1. Is JavaScript a Dynamic or Static language?
Javascript is a Dynamic language. It does not ask you to declare the types of the variables. In JavaScript, variables can hold different data types at different times. The variables are assigned a type during runtime depending on what value it is storing at that particular time.
let x = 111;
Here ‘x’ has data type of Number
x = “Intellipaat”;
Here ‘x’ has data type of String
2. Is JavaScript synchronous or asynchronous?
JavaScript is synchronous and single-threaded by default. It becomes asynchronous when using asynchronous operations like making HTTP requests, using timers, etc, or using web workers.
3. What are the different data types available in JS?
JavaScript has the following data types:
- Number – Stores integer and floating-point values.
let sum = 555;
let share = 55.55;
- BigInt – Introduced in ES11(ECMAScript 2020). It handles values which have an exceed maximum safe integer value.
let bigNumber = 8938123748264892374749279272187847874899n;
- String – Stores textual data.
let company = “Intellipaat”;
- Boolean – Can store only two values: true or false
let boolValue = false;
- Undefined – Undefined data type is given to a variable that has been declared but has not been given a value to hold.
let myValue;
- Null – Null is for specifying that the given variable does not hold any value but null.
let noValue = null;
- Symbol – This was introduced in ES6. It deals with creating unique values.
let uniqueValue = Symbol(“unique”);
- Object – Objects in JavaScript are like key-value pairs.
let company = { name: “Intellipaat”, employees: 200 };
4. State the difference between var, let, and const.
Early Javascript had only ‘var’ keywords to declare variables. Variables declared as ‘var’ are globally scoped or function scoped. In its given scope it can be redeclared as many times as needed.
Modern Javascript (ES6) introduced two new keywords ‘let’ and ‘const’ to declare variables. Variables declared with these two keywords are block-scoped and they cannot be reassigned in their given scope. Variables declared ‘let’ can be reassigned a new value in its scope but variables declared ‘const’ cannot be assigned a new value.
The following table will give you a gist of their differences:
Characteristics |
var |
let |
const |
Scope |
Function or Global Scoped |
Block-scoped |
Block-scoped |
Redeclaration(in the same scope) |
Yes |
No |
N0 |
Reassignable |
Yes |
Yes |
No |
Hoisting |
Yes |
Yes |
Yes |
Syntax |
var x = 10; |
let x = 10; |
const x = 10; |
Current Usage |
Not used much |
Used a lot |
Used a lot |
5. What is Hoisting in JavaScript?
In Javascript, one can use a variable or call a function even before they are declared in the code. This happens due to Hoisting which is a JavaScript feature. Hoisting declarations are moved to the top of their scope during compilation.
6. Can we change the value of the variable declared as const?
The answer is No. However, there are some situations in which the values can be changed. This can be explained with the help of a couple of examples.
Example 1 –
Say we have a variable ‘iAmConstant’ declared as const and storing a value of2000.
const iAmConstant = 2000;
Now, if we want to update its value in the following way –
iAmConstant = 5000;
This won’t work and will throw a TypeError.
Example 2 –
If we have an object xyz having data type const.
const xyz = {
times: 4
}
Now if we want to assign a new value to the entire object xyz like this –
xyz = {
message:”Say Hello”,
times: 5
}
It will again not work because const is block-scoped and cannot be redeclared in the same scope. It will throw an error saying – TypeError: Assignment to constant variable.
However, if we update the keys like this –
xyz.message = “Say Hello”;
xyz.times = 5;
The value of the object will get updated as its values are mutable and it won’t throw any error.
7. In how many ways can we declare a Function in JavaScript?
Functions in JavaScript can be declared in the following ways –
- Function as a Statement
- It starts with ‘function’ keyword
- It can return value or other function
- This function declaration gets hoisted to the top
Example –
function statement() {
console.log("Hello, I am a function declaration!");
}
statement();
- Function Expression
- Function is assigned to a variable
- Function can be anonymous i.e. not have a name
- It doesn’t get hoisted to the top
Example –
let expression = function(num1, num2) {
let sum = num1 + num2;
return sum;
}
- Arrow Function
- Arrow functions are also known as fat arrow functions. They were introduced in ES6. It is a way to shorten the usual traditional function.
- It does not have its own value of ‘this’ object
Example –
let add = (num1, num2) => num1 + num2;
- Immediately Invoked Function Expression
- Also known as IIFE in short
- This type of function declaration is executed immediately after it is defined.
Example –
(function() {
console.log("IIFE executed!");
})();
- Anonymous Function
Example –
setTimeout(function() {
console.log(“This is anonymous function!”);
}, 1000);
Master Web Development Today!
Learn to build stunning websites and powerful web applications with expert-led courses.
8. When do we need to use the ‘return’ statement with the arrow function?
Whenever there is more than one statement inside the arrow function then we need to use a return statement inside it, otherwise it is okay if we do not use it.
Example –
let add = (num1, num2) => {
if(num2 != 0){
return num1+num2;
}
}
let add = (num1, num2) => {
if(num2 != 0){
return num1+num2;
}
else return “Cannot be divided by zero”;
}
let add = (num1, num2) => {
if(num2 != 0){
return num1+num2;
}
}
9. Explain the map(). How is it different from foreach() method?
In JavaScript, we have a method called map(). This method loops over existing array elements and creates a new array post calculations. Since it returns a new array, it can be chained with other methods like filter(), reduce(), etc to perform the necessary calculations.
The foreach() method in JavaScript returns undefined, so we cannot perform any calculations on it. It can be used to perform side effects in arrays like logging or saving value to the database, etc.
10. What is the difference between ‘===’ and ‘==’ in Javascript?
=== |
== |
Compared both value and type of variable |
Compares only value of variable |
Does not perform type conversion |
Performs type conversion. It Converts value to similar type before comparing |
11. How can we flatten a 2D or 3D array in JavaScript?
Before ES8 to flatten a nested array one would have to make recursive calls to it to achieve it. To ease the work, ES8 has introduced a method called ‘array.flat(depth)’ to flatten any array.
- The default value of depth is 1. Which means by default it will only flatten to one level.
- We can pass parameters like 1, 2, 3, etc to flatten to the corresponding level.
- If the array is highly nested we can directly pass ‘Infinity’ to flatten the complete array at once.
Example –
const arr = [1, [2, [3, [4, [5]]]]];
console.log(arr.flat(Infinity));
Output –
[1,2,3,4,5]
Java Script Interview Questions for 2- 5 years
12. What is the easiest way to add an element to the beginning of an array in JavaScript?
To add an element to the beginning of an array, the easiest way is to use the method ‘array.unshift()’.
Example –
const myArray = [1,2,3,4,5];
myArray.unshift(10);
console.log(myArray);
Output –
[10,1,2,3,4,5]
Bonus: To remove an element at the beginning of an array use method ‘array.shift()’.
13. What is the use of Object.freeze?
Object.freeze is used if we want to freeze or fix the values of an object so that it cannot be changed or modified.
let frozenObject = { company: “Intellipaat”, employees: 200 }
Object.freeze(frozenObject);
frozenObject.company = “Google”; // This won’t work
14. What are Template Literals in JavaScript?
Template Literals denoted with “(backticks) were introduced in ES6. By using Template Literals we can easily concatenate strings. All we have to do is put the expression inside ‘${}’. This will help get rid of using the ‘+’ operator.
Example –
const name = ‘Intellipaat’;
const = 200;
console.log(`I am working with ${name}, and it has ${employeeCount}+ employees at the moment.`);
Output –
I am working with Intellipaat, and it has 200+ employees at the moment.
15. What is ‘this’ object in JavaScript?
In JavaScript ‘this’ stores the current context or reference of the current object from where it is called.
Example –
const obj = {
name: "Intellipaat",
print: function () {
console.log(this.name);
}
};
obj.print();
Output –
Intellipaat
16. Explain the difference between null and undefined.
If a variable has been intentionally assigned a value of NULL, it means it must store a value of null, which means no value.
In JavaScript ‘undefined’ is the default type of a variable. It remains undefined until we assign it a value.
Bonus: If we compare null and undefined using ‘==’, it will give the output as true.
console.log(null == undefined);
Output-
true
However, if we compare using ‘===’, it will give the output as false.
console.log(null === undefined);
Output –
false
17. What do you understand about Mutable and Immutable in the context of JavaScript?
In JavaScript, we have different data types, out of which some are mutable and some are immutable.
Mutable means that the value of such variables can be changed directly after their creation. Example – Arrays and Objects.
Immutable means their value cannot be changed post their creation. Examples – numbers, and strings.
18. What are Spread Operators in JavaScript?
Spread Operators (. . .) in JavaScript are used to “spread” the elements of an array or in JavaScript. By using Spread Operators we can copy output array/object values, merge them, pass these values to a function efficiently, etc. Let’s understand these concepts with some examples.
Example 1-
const arr = [1, 2, 3];
console.log(...arr);
Output-
1 2 3
Example 2-
const numbers = [1, 2, 3];
function add(a, b, c) {
return a + b + c;
}
console.log(add(...numbers));
Output-
6
Example 3-
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const merged = { ...obj1, ...obj2 };
console.log(merged);
Output-
{ a: 1, b: 2 }
19. What do you understand about Array destructuring in JavaScript?
Destructuring was introduced in JS ES6. It is used to unpack the values from the given array and assign them to unique variables.
Example –
const keywords= ["var", "let", "const"];
const [first, second, third] = keywords;
console.log(first);
console.log(second);
console.log(third);
Output-
“var”
“let”
“const”
Note: Destructuring can be used in a similar way with Objects as well.
Build Websites Like a Pro!
Learn. Code. Create: With our Expert- led Web Development Courses
20. What do you understand by Lexical Scoping?
Lexical Scoping in JavaScript means a function can use values declared in its parent’s scope but its parent cannot do the same. Lexical Scope implies the block of code in which a function or variable is declared.
Variables declared using the ‘var’ keyword are function-scoped which means their lexical scope lies within the function they are declared in.
Example:
function testVar() {
if (true) {
var x = 10; // This variable is “Function” and that is its “Lexical” scope
}
console.log(x); // 10 (accessible outside the block)
}
testVar();
Whereas variables declared with ‘let’ or ‘const’ keywords are block-scoped. Which means their lexical scope lies within a block, like, inside if, for or while blocks.
function testLet() {
if (true) {
let y = 20; // This variable is “Block” scoped and that is its “Lexical” scope
}
console.log(y); // ReferenceError: y is not defined (as it cannot be accessed outside its lexical scope.
}
testLet();
21. How to convert an array into an object and vice-versa?
- To convert an array into an object we can use a method named ‘fromEntries()’.
Example –
const entries = [
["name", "Intellipaat"], ["employees", 200]];
const newObject = Object.fromEntries(entries);
console.log(newObject);
Output-
{ name: ‘Intellipaat’, employees: 200 }
- To convert an Object to an Array we can use a method named ‘entries()’.
Example –
const user = {
name: "Intellipaat",
employees: 200
};
const newArray = Object.entries(user);
console.log(newArray);
Output-
[ [‘name’, ‘Intellipaat’], [’employees’, 200] ]
JavaScript Interview Questions for Experienced
22. How to perform deep freezing in a nested object?
To perform deep freezing in a nested object in JavaScript, you need to recursively apply Object.freeze() to every level of the object, including its nested properties. You can check if the data is frozen at each level by using Object.isFrozen().
You can do so by implementing the following code –
Step 1 – Implementing the deepFreeze function to freeze every object recursively.
function deepFreeze(obj)
{
Object.freeze(obj); // Iterate over all properties of the object
Object.getOwnPropertyNames(obj).forEach((prop) => {
const value = obj[prop];
// If the value is an object and not null, and hasn't been frozen yet, freeze it
if ( value !== null && typeof value === "object" && !Object.isFrozen(value) )
{
deepFreeze(value); // This will recursively call deepFreeze
} });
return obj; // Returns the frozen object
}
Step 2 – Call the function deepFreeze() and check if each object is frozen or not.
const nestedObject = {
level1: {
level2: {
level3: {
key: "value",
},
},
anotherKey: "anotherValue",
},
};
const frozenObject = deepFreeze(nestedObject);
// Trying to modify properties
frozenObject.level1.level2.level3.key = "newValue"; // This will not work now
delete frozenObject.level1.level2; // This will not work now
frozenObject.newProp = "test"; // This will not work now
console.log(frozenObject);
// Check if the object is frozen
console.log(Object.isFrozen(frozenObject)); // This will print
true
console.log(Object.isFrozen(frozenObject.level1)); //This will print
true
console.log(Object.isFrozen(frozenObject.level1.level2)); // This will print
true
console.log(Object.isFrozen(frozenObject.level1.level2.level3)); // This will print true
Output-
{
level1: {
level2: {
level3: { key: "value" }
},
anotherKey: "anotherValue"
}
}
true
true
true
true
23. What is the significance of Closures in JavaScript?
Closure allows the inner function to remember the scope in which it was created even after the outer function has finished executing which includes remembering variables from the outer function’s scope
function add(x)
{
return function(y)
{
return(x+y);
};
}
var add5 = add(10);
var add10 = add(20);
console.log(add5(50));
console.log(add10(30));
Output –
60
50
Note: Here add5 and add10 are both closures as they share the same function body definition but have different lexical environments.
24. Higher Order Function vs Callback function?
A Higher Order Function is one that takes another function as an argument.
Whereas a Callback function is one that is passed to another function as an argument.
Example –
const calculator = (num1,num2, operator) => operator(num1, num2);
const subs = (a,b) => return (a-b);
const add = (a,b) => return (a+b);
console.log(calculator(20,10, subs));
console.log(calculator(20,10, add));
Here, the calculator is a HOF, as it is taking another function as a parameter. Whereas, ‘subs’ and ‘add’ are callback functions that are being passed to another function as a parameter.
25. What do you understand by Currying?
When a function takes one argument and returns a new function to handle new arguments, it will go on until all arguments are provided and the result is computed. This is called Currying.
Example –
currying(1)(11)(111);
function currying(num1) {
return function(num2){
return function(num3) {
console.log(num1, num2, num3);
}
}
}
26. How does the JavaScript event loop work, and what role do the call stack, task queue, and microtask queue play in it?
The answer to this question can be explained step by step in the following way –
- JavaScript executes synchronous code using a call stack (LIFO – Last In, First Out). Each function call is pushed onto the stack and popped off once it finishes executing.
- Then we have an event loop in JavaScript that continually checks the call stack and task queues to manage the execution of synchronous and asynchronous code. It ensures the call stack is empty before picking tasks from the queues.
- JavaScript has Task Queues which are of the following types:
- Macrotask Queue (Task Queue): Holds tasks like setTimeout, setInterval, setImmediate (Node.js), and I/O operations.
- Microtask Queue: Holds tasks like Promise.then, MutationObserver, and process.nextTick (Node.js). Microtasks have higher priority and are executed before macrotasks.
Predict the Output
27. Predict the Output of the following code.
function abc(){
for(let i =0; i<5; i++){
setTimeout(function () {
console.log(i);
}, 1000)
}}
abc();
The output of this code will be printed in intervals of 10 seconds like this –
0
1
2
3
4
Explanation: let is block scoped. Everytime the value it takes is different, so it prints a different value.
28. Predict the Output of the following code.
function abc(){
for(var i =0; i<5; i++){
setTimeout(function () {
console.log(i);
}, 1000)
}}
abc();
The output of this code will be printed in intervals of 10 seconds like this –
5
5
5
5
5
Explanation: ‘var’ is a function or global scope. Everytime the value it takes is different, so by the time the loop ends the value of i=5, so it prints 5.
29. In what order will the output be printed?
function abc(){
setTimeout(function () {
console.log(“SetTimeOut”);
}, 0)
Promise.resolve(“Promise Resolved”).then(res => console.log(“Promise Resolved”);
console.log(“Hi”);
}
abc();
The sequence of output will be –
Hi
Promise Resolved
SetTimeOut
Explanation: First JavaScript executes console.log(“Hi”), because it is a synchronous code, so it gets the first priority.
Next out of promise and timer JavaScript always prioritizes microtasks like network calls over regular tasks like timeouts)
30. Predict the Output of the following code.
let company = { name: 'Intellipaat', employees: 200 };
let company2 = company;
company2.name = 'Google';
console.log(company);
console.log(company2);
The output of the above code will be –
{ name: ‘Google’, employees: 200 }
{ name: ‘Google’, employees: 200 }
Explanation: The reason both objects are printing the same value is because both company and company2 refer to the same memory space. This is because in JavaScript objects are reference types. To solve this you can use spread operators (. . .), which will create a shallow copy of the object.
Example –
let company = { name: 'Intellipaat', employees: 200 };
let company2 = { ...company }; // Creates a shallow copy
company2.name = 'Google';
console.log(company);
console.log(company2);
Output –
{ name: 'Intellipaat', employees: 200 }
{ name: 'Google', employees: 200 }
31. Predict the Output of the following code.
function outer() {
let count = 0;
function inner() {
count++;
console.log(count);
}
return inner;
}
const fn1 = outer();
const fn2 = outer();
fn1();
fn1();
fn2();
fn1();
Output-
1
2
1
3
Explanation: Each call to outer() creates a new closure with its own count variable initialized to 0. When fn1 and fn2 are created, they each retain access to their own separate count variable due to lexical scoping. As a result, calls to fn1() increment its count independently of fn2(), ensuring they do not interfere with each other.
Get 100% Hike!
Master Most in Demand Skills Now!
Conclusion
This brings me to the end of this article. I am sure it must have been a great read and you might have stumbled into a lot of new concepts and questions. With this, I wish you all the best in your interviews. If you want to explore more and master the skills in this domain you can enroll in Intellipaat’s Website Development Courses today!