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 the value of the variable |
Does not perform type conversion |
Performs type conversion. It Converts value to a 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]
12. What are higher-order functions in JavaScript?
Higher order functions are defined as the functions that take one or more functions as arguments, and/or functions that return a function as its value.
Example: Let’s look at some examples, of JavaScript inbuilt functions like map() and
filter() are higher-order functions.
const num = [1, 2, 3, 4, 5];
Let squares = num.map(x => x** 2);
console.log(squares);
13. What are Arrow functions?
Arrow functions are shorthand syntax for writing functions in JavaScript. The arrow functions do not have their own ‘this’ or ‘arguments’.
Example:
//Normal function
function add(a,b){
return a+b
}
//Arrow function
const add = (a, b) => a + b;
14. What are truthy and falsy values?
Truthy values are values that evaluate to true when coerced to a boolean, whereas Falsy values are values that evaluate to false when coerced to a boolean. There are 6 types of falsy values in JavaScript: false, 0, “” empty string, null, undefined, and NaN.
15. What are JavaScript Arrays?
JavaScript Array is a type of object that is used to store a collection of values. The array can store values of any data type. Ex: string, number, boolean, or array of objects
Example of Array:
let arr = [1,2,3] //number array
let arr2 = [“a”,”b”,”c”]// string array
16. What is the JavaScript DOM?
The Document Object Model, or DOM, is a map of a webpage that can be modified by using JavaScript. It represents the webpage as a tree of parts like headings, paragraphs, and links. Each part is a “node” in the tree. With JavaScript, you can find these parts using methods like getElementById and change their content, style, or structure.
17. What would be the result of 5+3+”10″?
Here, 5 and 3 behave like an integer, and “10” behaves like a string. So 5 + 3 will be 8. Then the output will be 5+”10″ = 510.
18. What is a template literal in JavaScript?
A template literal in JavaScript is a way to create strings using backticks (`), which makes string manipulation easier. Unlike regular strings, template literals allow you to embed expressions inside the string using ${}.
19. What are errors in JavaScript?
There are three types of errors in JavaScript:
Syntax error: Syntax error is a type of error that comes when an individual is typing some strings of characters or tokens in some particular programming language.
Logical error: A logical error is a type of tool flaw that makes its execution wrong and its operation incomplete.
Runtime Error: A runtime is an error that is usually encountered when the program is in the process of executing.
JavaScript Interview Questions for Experienced
20. What are JavaScript modules?
JavaScript modules are used in order to divide the JavaScript code into certain components. They are applied in order to load several variables, functions, or objects in a file and to send several variables, functions, or objects in another file. The keywords import and export are used to read the files and export write into other files respectively.
Example:
// In file1.js
export const var1= () => "Hi user";
// In file2.js
import { var1} from './file1';
console.log(var2());
21. What is an event bubbling in JavaScript?
In JavaScript event bubbling is the phenomenon where an event, for instance, the click event starts at the element and then moves up through the entire parents DOM nodes. For example, when you click a button inside a div, the event is inaugurated on the button and then bubbles through the div and then through any of its parents contingent on the event’s propagation model, up to the root. This enables one to work with events on parent of which one cannot add a listener to each child. This propagation can be halted by event.stopPropagation() which means that the event does not migrate to the parent element.
22. What is memoization in JavaScript?
Memoization in JavaScript refers to a technique of optimizing function by storing the values of function calls and instead of executing the function, the result is returned if the parameters match that of the previous calls. This can stop the calculation work from being spread across repeat calls of the function and make it more efficient,t especially when the function uses the same argument values many times.
Example:
const cache = {};
function add(num) {
if (num in cache) {
return cache[num]; // Return cached result
}
cache[num] = num + 10; // Store result in cache
return cache[num];
}
console.log(add(5)); // Calculates and stores 15
console.log(add(5)); // Returns cached 15
23. What is event delegation in JavaScript?
Event delegation is a technique of JavaScript in which a parent element listens to the defined events of the child elements using event bubbling. This also assists in minimizing circumstances when several event listeners are written in the code.
24. What is debouncing?
Ans. Debouncing is a programming technique used to improve the performance of web applications by limiting the rate at which a function is executed. This is especially useful for event-driven actions like resizing the window, searching as you type, or scrolling, where rapid firing of events can negatively impact performance.
Example:
function debounce(func, delay) {
let timer;
return function (...args) {
const context = this;
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(context, args);
}, delay);
};
}
25. What is callback hell?
Ans. Callback hell occurs in JavaScript when numerous nested callbacks create a complex, deeply indented code structure, commonly known as the “pyramid of doom.” This makes the code hard to read, debug, and maintain, ultimately resulting in reduced code quality and challenges with scalability.
Example:
getData(function(data) {
processData(data, function(processedData) {
saveData(processedData, function(savedData) {
sendConfirmation(savedData, function(response) {
console.log("Operation completed: " + response);
});
});
});
});
26. 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()’.
27. 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
28. 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.
29. 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
30. 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
31. 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 after their creation. Examples – numbers, and strings.
32. 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 }
33. 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
34. 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. This 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();
35. 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 5 years Experience
36. What are async and await keywords in JavaScript?
Async and Await keywords in JavaScript are used for working with asynchronous operations employing JavaScript promises.
Async
Async in JavaScript is used as a tag to describe an asynchronous function. The Async keyword results in a promise.
Example:
async function functionName() {
// Function body
}
Await
Await is used in JavaScript inside the async function and its function is to wait until a promise is either resolved or rejected.
Example:
let result = await somePromise;
37. Difference between Java and JavaScript
Java: The basics of Java are that it is an object-oriented programming language. In the years of the rise of computer science and information technologies, it was one of the most popular languages for programming. Because of its virtual machine platform and an object-oriented program language, one can compile programs virtually for any kind of platform.
JavaScript: JavaScript is a scripting language of the client side. JavaScript is a lightweight computer language that comes into the category of scripting language which is used to develop an interactive website. It can also animate dynamically added text to HTML components.
38. What are web workers in JavaScript?
In JavaScript, Web Workers let run scripts in background threads apart from the main thread and hence contribute to carrying out heavy tasks that do not lock the interface. They enhance efficiency because certain processes – computations, data processing, image manipulation – can run concurrently. Web Workers use postMessage and onmessage to interact with the main thread but it is prohibited to touch the DOM and window.
39. What is currying in JavaScript?
Currying in JavaScript is functional programming which is technique that turns a function with multiple arguments into a sequence of functions each of which expects a single argument.
Example:
function curriedAdd(a) {
return function(b) {
return a + b;
};
}
const addTwo = curriedAdd(2);
console.log(addTwo(3));
40. What is prototype inheritance?
Prototype inheritance in JavaScript is a technique that allows objects to inherit properties and methods from other objects. In JavaScript, every object has an internal link to its prototype, which is another object. The prototype chain is made up of these prototypes.
Example:
// constructor function
function fun(name) {
this.name = name;
}
// Add a method to the prototype
fun.prototype.var = function() {
return `Hello, I am ${this.name}.`;
};
// Create an object
const intelli = new fun('Intellipaat');
// Access a property and a prototype method
console.log(intelli.name);
console.log(intelli.var());
41. 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
<strong>Output-</strong>
{
level1: {
level2: {
level3: { key: "value" }
},
anotherKey: "anotherValue"
}
}
true
true
true
true
42. 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.
43. 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 an HOF, as it takes another function as a parameter. Whereas, ‘subs’ and ‘add’ are callback functions that are being passed to another function as a parameter.
44. 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);
}
}
}
45. 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 macro tasks.
Predict the Output
46. 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’s block scoped. Every time the value it takes is different, so it prints a different value.
47. 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. Every time the value it takes is different, so by the time the loop ends the value of i=5, so it prints 5.
48. 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)
49. 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 }
50. 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 their 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!