Engineer's Tutorial
Aug 16, 202415 min read
Top 50 JavaScript Interview Questions with Code Examples
RY

Rohan Yadav

Full stack developer

Table of contents

JavaScript Interview Questions

JavaScript is one of the most popular programming languages, making it crucial for web development. If you're preparing for a JavaScript interview, this blog will help you cover essential topics and understand the reasoning behind them.

Go to top ↑
 1. What are the different data types in JavaScript? Go to Top ↓

JavaScript has several primitive data types:
Number
String
Boolean
Undefined
Null
Symbol (ES6)
BigInt (ES11)

let num = 42;          // Number
let str = "Hello";     // String
let isTrue = true;     // Boolean
let notDefined;        // Undefined
let emptyValue = null; // Null
let symbol = Symbol(); // Symbol
let bigIntNum = 9007199254740991n; // BigInt

 
2. Explain the difference between == and === in JavaScript.

== checks for equality after type coercion.
=== checks for equality without type coercion (strict equality).

console.log(5 == "5");  // true (type coercion)
console.log(5 === "5"); // false (no type coercion)

3. What is a closure in JavaScript?

A closure is a function that remembers the environment in which it was created, even after that environment has gone.

function outer() {
   let count = 0;
   return function inner() {
       count++;
       console.log(count);
   }
}
const increment = outer();
increment(); // 1
increment(); // 2

 4. How do you create an object in JavaScript?

You can create an object using object literals, the Object constructor, or classes (ES6).

// Using object literal
const obj1 = { name: "John", age: 30 };
// Using Object constructor
const obj2 = new Object();
obj2.name = "John";
obj2.age = 30;
// Using a class
class Person {
   constructor(name, age) {
       this.name = name;
       this.age = age;
   }
}
const obj3 = new Person("John", 30);

5. Explain the concept of this in JavaScript.

The this keyword refers to the object from which the function was called.

const person = {
   name: "John",
   greet: function() {
       console.log("Hello, " + this.name);
   }
}
person.greet(); // Hello, John

6. What is the event loop in JavaScript?

The event loop is a mechanism that allows JavaScript to perform non-blocking operations by offloading operations to the browser (like I/O tasks) and adding callback functions to the task queue.

console.log("Start");
setTimeout(() => {
   console.log("Timeout");
}, 0);
console.log("End");
// Output:
// Start
// End
// Timeout

7. What is the difference between null and undefined?

null is an assignment value that represents "no value."
undefined means a variable has been declared but not assigned a value.

let x;
console.log(x); // undefined
let y = null;
console.log(y); // null

8. What are arrow functions, and how are they different from regular functions?

Arrow functions are a shorthand for writing functions in ES6. They differ from regular functions in that they do not have their own this, arguments, super, or new.target.

const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
// Regular function
function addRegular(a, b) {
   return a + b;
}
console.log(addRegular(2, 3)); // 5

9. Explain the concept of hoisting in JavaScript.

Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope.

console.log(x); // undefined (due to hoisting)
var x = 5;
console.log(y); // ReferenceError: y is not defined
let y = 10;

10. What are Promises in JavaScript?

Promises are objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value.

 const promise = new Promise((resolve, reject) => {
   setTimeout(() => {
       resolve("Success!");
   }, 1000);
});
promise.then(value => console.log(value)); // "Success!" after 1 second

11. What is the difference between var, let, and const?

var is function-scoped and can be redeclared.
let is block-scoped and cannot be redeclared.
const is block-scoped and cannot be redeclared or reassigned.

var x = 1;
var x = 2; // No error
let y = 1;
y = 2; // No error
const z = 1;
z = 2; // Error: Assignment to constant variable. 

12. What are higher-order functions in JavaScript?

Higher-order functions are functions that take other functions as arguments or return functions as their result.

function higherOrder(fn) {
   return function() {
       console.log("Before");
       fn();
       console.log("After");
   }
}
function sayHello() {
   console.log("Hello");
}
const wrappedFunction = higherOrder(sayHello);
wrappedFunction();
// Output:
// Before
// Hello
// After

13. What are the differences between call, apply, and bind?

call: Invokes a function with a given this value and arguments provided individually.
apply: Invokes a function with a given this value and arguments provided as an array.
bind: Returns a new function, allowing you to pass a this value and arguments to the original function.

function greet(greeting, punctuation) {
   console.log(greeting + ', ' + this.name + punctuation);
}
const person = { name: 'John' };
greet.call(person, 'Hello', '!'); // Hello, John!
greet.apply(person, ['Hi', '.']); // Hi, John.
const boundGreet = greet.bind(person, 'Hey');
boundGreet('?'); // Hey, John?

14. Explain the concept of prototypes in JavaScript.

Every object in JavaScript has a prototype. A prototype is also an object that has its own prototype, forming a chain known as the prototype chain.

function Person(name) {
   this.name = name;
}
Person.prototype.sayHello = function() {
   console.log("Hello, " + this.name);
}
const john = new Person("John");
john.sayHello(); // Hello, John

15. What is the async/await syntax in JavaScript?

async/await is a modern syntax for handling asynchronous operations, built on top of Promises, making asynchronous code look synchronous.

function resolveAfter2Seconds() {
   return new Promise(resolve => {
       setTimeout(() => {
           resolve('resolved');
       }, 2000);
   });
}
async function asyncCall() {
   console.log('Calling...');
   const result = await resolveAfter2Seconds();
   console.log(result); // resolved after 2 seconds
}
asyncCall();

16. What is the difference between forEach and map in JavaScript?

forEach: Executes a provided function once for each array element.
map: Creates a new array populated with the results of calling a provided function on every element in the calling array.

const arr = [1, 2, 3];
arr.forEach((num, index) => {
   arr[index] = num * 2;
});
console.log(arr); // [2, 4, 6]
const doubled = arr.map(num => num * 2);
console.log(doubled); // [4, 8, 12]

17. What is the purpose of Array.prototype.reduce in JavaScript?

reduce executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

const arr = [1, 2, 3, 4];
const sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 10

18. What are template literals in JavaScript?

Template literals allow embedded expressions, multiline strings, and string interpolation, making string construction easier and more readable.

const name = "John";
const age = 30;
const message = `My name is ${name} and I
am ${age} years old.`;
console.log(message); // My name is John and I am 30 years old.

19. What is destructuring in JavaScript?

Destructuring is a syntax that allows you to unpack values from arrays or properties from objects into distinct variables.

// Array Destructuring
const [a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2
// Object Destructuring
const { name, age } = { name: "John", age: 30 };
console.log(name); // John
console.log(age); // 30

20. What is the difference between synchronous and asynchronous code in JavaScript?

Synchronous code is executed line by line; each operation waits for the previous one to complete.
Asynchronous code allows operations to run concurrently, using callbacks, Promises, or async/await to handle the results.

// Synchronous
console.log('Sync 1');
console.log('Sync 2');
// Asynchronous
console.log('Async 1');
setTimeout(() => console.log('Async 2'), 1000);
console.log('Async 3');

21. How do you check if a variable is an array in JavaScript?

You can check if a variable is an array using Array.isArray() or instanceof Array.

 let arr = [1, 2, 3];
console.log(Array.isArray(arr)); // true
console.log(arr instanceof Array); // true

22. What is the difference between Array.prototype.find and Array.prototype.filter?

find: Returns the first element that satisfies the provided testing function.
filter: Returns a new array with all elements that satisfy the provided testing function.

const arr = [1, 2, 3, 4, 5];
const found = arr.find(element => element > 3);
console.log(found); // 4
const filtered = arr.filter(element => element > 3);
console.log(filtered); // [4, 5]

23. What is the purpose of Array.prototype.slice in JavaScript?

slice returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included).

const arr = [1, 2, 3, 4, 5];
const sliced = arr.slice(1, 3);
console.log(sliced); // [2, 3]

24. What is the difference between Array.prototype.splice and Array.prototype.slice?

splice: Modifies the original array by adding/removing elements.
slice: Does not modify the original array and only returns a shallow copy of a portion of the array.

const arr = [1, 2, 3, 4, 5];
// Slice
const sliced = arr.slice(1, 3);
console.log(sliced); // [2, 3]
console.log(arr); // [1, 2, 3, 4, 5]
// Splice
const spliced = arr.splice(1, 2);
console.log(spliced); // [2, 3]
console.log(arr); // [1, 4, 5]

25. How do you remove duplicates from an array in JavaScript?

You can remove duplicates by using Set or by filtering the array.

const arr = [1, 2, 2, 3, 4, 4, 5];
// Using Set
const uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // [1, 2, 3, 4, 5]
// Using filter
const uniqueArr2 = arr.filter((value, index, self) => self.indexOf(value) === index);
console.log(uniqueArr2); // [1, 2, 3, 4, 5]

26. What is the purpose of the typeof operator in JavaScript?

typeof is used to determine the type of a variable or expression.

console.log(typeof 42);       // "number"
console.log(typeof "Hello");  // "string"
console.log(typeof true);     // "boolean"
console.log(typeof undefined);// "undefined"
console.log(typeof null);     // "object" (this is a quirk in JavaScript)
console.log(typeof {});       // "object"
console.log(typeof Symbol()); // "symbol"

27. What is the difference between Object.freeze and Object.seal?

Object.freeze: Makes an object immutable; you cannot add, delete, or modify properties.
Object.seal: Prevents adding or deleting properties, but allows modifying existing properties.

const obj = { name: "John" };
Object.freeze(obj);
obj.name = "Doe";  // No effect
obj.age = 30;      // No effect
console.log(obj);  // { name: "John" }
const obj2 = { name: "John" };
Object.seal(obj2);
obj2.name = "Doe"; // Works
obj2.age = 30;     // No effect
console.log(obj2); // { name: "Doe" }

28. What is the purpose of the new keyword in JavaScript?

The new keyword is used to create an instance of a user-defined object type or one of the built-in object types that has a constructor function.

function Person(name, age) {
   this.name = name;
   this.age = age;
}
const john = new Person("John", 30);
console.log(john.name); // John
console.log(john.age);  // 30

29. What is an Immediately Invoked Function Expression (IIFE)?

An IIFE is a function that is executed immediately after it is defined.

(function() {
   console.log("IIFE");
})();
// Output: IIFE

30. Explain the concept of memoization in JavaScript.

Memoization is a technique to speed up functions by storing their results. If the function is called with the same arguments again, the stored result is returned instead of recalculating it.

function memoizedAddTo80() {
   let cache = {};
   return function(n) {
       if (n in cache) {
           return cache[n];
       } else {
           console.log("Calculating...");
           cache[n] = n + 80;
           return cache[n];
       }
   }
}
const memoAdd = memoizedAddTo80();
console.log(memoAdd(5));  // Calculating... 85
console.log(memoAdd(5));  // 85 (from cache)

31. What are the different ways to iterate over an array in JavaScript?

You can iterate over an array using a for loop, for...of loop, forEach, map, or for...in loop.

const arr = [1, 2, 3];
// for loop
for (let i = 0; i < arr.length; i++) {
   console.log(arr[i]);
}
// for...of loop
for (let num of arr) {
   console.log(num);
}
// forEach
arr.forEach(num => console.log(num));
// map
arr.map(num => console.log(num));
// for...in loop (usually for objects)
for (let index in arr) {
   console.log(arr[index]);
}

32. What is the difference between Object.keys(), Object.values(), and Object.entries()?

Object.keys(): Returns an array of a given object's property names.
Object.values(): Returns an array of a given object's property values.
Object.entries(): Returns an array of a given object's own enumerable string-keyed property [key, value] pairs.

const obj = { a: 1, b: 2, c: 3 };
console.log(Object.keys(obj));    // ["a", "b", "c"]
console.log(Object.values(obj));  // [1, 2, 3]
console.log(Object.entries(obj)); // [["a", 1], ["b", 2], ["c", 3]]

33. How do you deep clone an object in JavaScript?

Deep cloning can be done using JSON.parse(JSON.stringify(obj)), but this method has limitations (e.g., it does not work with functions, undefined, or Symbol). A more robust way is to use libraries like Lodash, or recursive functions.

const obj = { a: 1, b: { c: 2 } };
// Using JSON
const clone = JSON.parse(JSON.stringify(obj));
console.log(clone); // { a: 1, b: { c: 2 } }
// Using Lodash
// const _ = require('lodash');
// const cloneDeep = _.cloneDeep(obj);
// console.log(cloneDeep); // { a: 1, b: { c: 2 } }

34. What is a callback function in JavaScript?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of action.

function greeting(name) {
   console.log('Hello ' + name);
}
function processUserInput(callback) {
   const name = 'John';
   callback(name);
}
processUserInput(greeting); // Hello John

35. What is the purpose of Array.prototype.sort in JavaScript?

sort sorts the elements of an array in place and returns the array. The default sort order is according to string Unicode code points.

const arr = [5, 2, 9, 1, 5, 6];
arr.sort();
console.log(arr); // [1, 2, 5, 5, 6, 9]
arr.sort((a, b) => a b); // Ascending order
console.log(arr); // [1, 2, 5, 5, 6, 9]
arr.sort((a, b) => b a); // Descending order
console.log(arr); // [9, 6, 5, 5, 2, 1]

36. Explain the concept of function currying in JavaScript.

Currying is the process of transforming a function that takes multiple arguments into a sequence of functions that each take a single argument.

function add(a) {
   return function(b) {
       return a + b;
   }
}
const add5 = add(5);
console.log(add5(10)); // 15

37. What is the difference between slice() and substring()?

slice(): Extracts a part of a string and returns it as a new string, without modifying the original string.
substring(): Similar to slice(), but it doesn't accept negative indices.

const str = "Hello, world!";
console.log(str.slice(0, 5)); // Hello
console.log(str.substring(0, 5)); // Hello
console.log(str.slice(-6, -1)); // world
console.log(str.substring(-6, -1)); // Hello, world! (substring treats negatives as 0)

38. What is the difference between JSON.stringify() and JSON.parse()?

JSON.stringify(): Converts a JavaScript object or value to a JSON string.
JSON.parse(): Parses a JSON string, constructing the JavaScript value or object described by the string.

const obj = { name: "John", age: 30 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // {"name":"John","age":30}
const parsedObj = JSON.parse(jsonString);
console.log(parsedObj); // { name: 'John', age: 30 }

39. What are the differences between function and class declarations?

A function declaration creates a function that can be invoked.
A class declaration creates a class that can be instantiated with the new keyword.

// Function Declaration
function Person(name) {
   this.name = name;
}
Person.prototype.greet = function() {
   console.log("Hello, " + this.name);
};
const john = new Person("John");
john.greet(); // Hello, John
// Class Declaration (ES6)
class Animal {
   constructor(name) {
       this.name = name;
   }
   speak() {
       console.log(this.name + ' makes a noise.');
   }
}
const dog = new Animal('Dog');
dog.speak(); // Dog makes a noise.

40. Explain the concept of this keyword in the context of different function types in JavaScript.

The this keyword refers to the object from which a function was called. However, its behavior changes depending on how the function is defined and called:
Regular functions: this refers to the object that called the function.
Arrow functions: this is lexically bound, meaning it uses this from the surrounding context.

const obj = {
   name: 'John',
   regularFunction: function() {
       console.log(this.name);
   },
   arrowFunction: () => {
       console.log(this.name);
   }
};
obj.regularFunction(); // John
obj.arrowFunction(); // undefined (because arrow functions don't have their own `this`)
 

41. How do you create a shallow copy of an object in JavaScript?

You can create a shallow copy using Object.assign() or the spread operator {...}.

const obj = { a: 1, b: { c: 2 } };
// Using Object.assign
const copy1 = Object.assign({}, obj);
// Using spread operator
const copy2 = { ...obj };
console.log(copy1); // { a: 1, b: { c: 2 } }
console.log(copy2); // { a: 1, b: { c: 2 } }

42. What is the difference between == and === in JavaScript?

== checks for equality with type coercion.
=== checks for equality without type coercion.

console.log(1 == '1'); // true
console.log(1 === '1'); // false

43. How does the new keyword work in JavaScript?

The new keyword creates an instance of a user-defined object type or one of the built-in object types that has a constructor function.

function Person(name) {
   this.name = name;
}
const john = new Person("John");
console.log(john.name); // John

44. What is the purpose of the apply method in JavaScript?

The apply method calls a function with a given this value and arguments provided as an array (or an array-like object).

function greet(greeting, punctuation) {
   console.log(greeting + ', ' + this.name + punctuation);
}
const person = { name: 'John' };
greet.apply(person, ['Hello', '!']); // Hello, John!

45. Explain how try...catch works in JavaScript.

The try...catch statement allows you to test a block of code for errors (try), and handle the error (catch).

try {
   let x = undefinedVariable;
} catch (error) {
   console.log(error.message); // undefinedVariable is not defined
}

46. What is the purpose of async/await in JavaScript?

async/await is a way to write asynchronous code in a synchronous manner. The async keyword is used to declare an asynchronous function, and await is used to pause the execution of the function until the promise is resolved.

async function fetchData() {
   const response = await fetch('https://api.example.com/data');
   const data = await response.json();
   console.log(data);
}
fetchData();

47. What is the difference between Array.prototype.map and Array.prototype.forEach?

map: Creates a new array populated with the results of calling a provided function on every element in the calling array.
forEach: Executes a provided function once for each array element but does not return a new array.

const arr = [1, 2, 3, 4, 5];
const mapped = arr.map(x => x * 2);
console.log(mapped); // [2, 4, 6, 8, 10]
arr.forEach((x, index) => {
   arr[index] = x * 2;
});
console.log(arr); // [2, 4, 6, 8, 10]

48. Explain the concept of event bubbling and event capturing in JavaScript.

Event bubbling: The event starts from the target element and bubbles up to the ancestor elements.
Event capturing: The event is first captured by the ancestor elements and propagated to the target element.

document.getElementById("child").addEventListener("click", () => {
   console.log("Child clicked");
}, true); // true for capturing phase
document.getElementById("parent").addEventListener("click", () => {
   console.log("Parent clicked");
}, false); // false (default) for bubbling phase

49. How do you debounce a function in JavaScript?

Debouncing ensures that a function is not called too frequently. It delays the execution of the function until after a specified time has passed since it was last invoked.

function debounce(func, wait) {
   let timeout;
   return function(...args) {
       clearTimeout(timeout);
       timeout = setTimeout(() => func.apply(this, args), wait);
   };
}
const processChange = debounce(() => console.log("Processing change"), 300);
window.addEventListener('resize', processChange);

50. What is the difference between localStorage and sessionStorage in JavaScript?

localStorage: Data persists even after the browser is closed.
sessionStorage: Data is only available for the duration of the page session.

// localStorage
localStorage.setItem('key', 'value');
console.log(localStorage.getItem('key')); // value
// sessionStorage
sessionStorage.setItem('key', 'value');
console.log(sessionStorage.getItem('key')); // value
Go to bottom ↓

 

Happy Coding!