Top 100 JavaScript Interview Questions for 2024: A Comprehensive Guide for Freshers and Mid-Level Developers
Introduction
JavaScript is a fundamental language for web development, widely used across frontend and backend applications. Whether you are a fresher just stepping into the world of programming or a mid-level developer looking to sharpen your skills, acing a JavaScript interview can be a key to unlocking great career opportunities.
This guide will walk you through the Top 100 JavaScript Interview Questions for 2024, providing detailed answers and explanations to help you understand the core concepts. Let’s dive deep into the topics that are likely to be on any interviewer’s list.
1. What is JavaScript, and how does it differ from other programming languages?
JavaScript is a high-level, interpreted scripting language primarily used to create dynamic and interactive content on the web. It differs from languages like Java or Python because it’s designed for the web, often executed directly in browsers, and can be both event-driven and asynchronous.
- Explanation: Unlike static languages like C or Java, JavaScript doesn’t require compilation. It’s a just-in-time (JIT) compiled language, meaning that it runs in the browser, interpreted by the engine (like Chrome’s V8 engine), making it suitable for interactive web experiences.
2. Explain the difference between let
, var
, and const
in JavaScript.
var
: Declares variables globally or function-scoped and allows redeclaration.let
: Block-scoped, does not allow redeclaration within the same scope.const
: Block-scoped, and once assigned, the value cannot be reassigned.- Explanation: In modern JavaScript,
var
is rarely used due to its global scope tendencies, which can lead to unexpected bugs.let
andconst
are part of ES6, which are more predictable, especially in block-scoped contexts like loops and conditional statements.
3. What is Hoisting in JavaScript?
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.
- Explanation: While only declarations are hoisted, not initializations, it explains why you can reference functions or
var
-declared variables before their actual declaration in the code.
console.log(a); // undefined
var a = 5;
hoistedFunction(); // works fine
function hoistedFunction() {
console.log('Hoisted');
}
4. What is the Temporal Dead Zone?
The Temporal Dead Zone (TDZ) is a behavior where variables declared with let
or const
cannot be accessed before their declaration, even though they are hoisted.
- Explanation: Unlike
var
, accessinglet
orconst
before their declaration results in aReferenceError
, ensuring better control and predictability in the code.
5. What are closures in JavaScript?
A closure is a function that retains access to variables from its parent scope, even after the parent function has returned.
- Example:
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
}
}
const counter = outer();
counter(); // 1
counter(); // 2
- Explanation: Closures are useful in scenarios like data hiding and creating private variables.
6. What is the difference between ==
and ===
?
==
: Compares two values for equality, performing type conversion if necessary.===
: Strict equality operator that checks both value and type.- Explanation: For predictable results, it’s best to use
===
to avoid unexpected type coercion.
7. What are Arrow Functions?
Arrow functions, introduced in ES6, provide a concise syntax for writing functions and inherit the this
value from the surrounding context.
const sum = (a, b) => a + b;
- Explanation: Unlike regular functions, arrow functions do not bind their own
this
value, making them ideal for use in methods or event listeners where the surrounding context’sthis
should be maintained.
8. Explain Event Delegation in JavaScript.
Event delegation is a technique where you attach a single event listener to a parent element to manage events on its child elements.
- Explanation: This improves performance by reducing the number of event listeners and makes dynamic element handling easier.
9. What is the Event Loop in JavaScript?
The Event Loop is the mechanism that handles asynchronous operations in JavaScript, ensuring non-blocking execution while waiting for callbacks.
- Explanation: JavaScript uses a single-threaded event loop to manage asynchronous tasks. The loop picks up events from the callback queue and executes them after the current call stack is cleared.
10. What are Promises in JavaScript?
A Promise represents an asynchronous operation that can be in one of three states: pending, fulfilled, or rejected.
- Example:
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => resolve('Success'), 1000);
});
myPromise.then(response => console.log(response));
- Explanation: Promises simplify asynchronous code, making it easier to manage success and failure scenarios.
11. Explain Async/Await.
Async/await is syntactic sugar built on top of promises to handle asynchronous operations more readably.
- Example:
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}
- Explanation: It allows you to write asynchronous code in a way that looks synchronous, simplifying error handling with
try/catch
.
12. What is the difference between null
and undefined
?
null
: Explicitly means “no value.”undefined
: Means a variable has been declared but not yet assigned a value.- Explanation: While both represent the absence of value,
null
is assigned deliberately, whereasundefined
occurs naturally when a variable is declared but not initialized.
13. What are Higher-Order Functions in JavaScript?
A higher-order function is a function that either takes a function as an argument or returns a function as a result.
- Example:
function higherOrder(fn) {
return function() {
fn();
};
}
- Explanation: These functions are useful in functional programming paradigms and are commonly used in methods like
map()
,filter()
, andreduce()
.
14. What is this
in JavaScript?
The value of this
in JavaScript depends on the context in which a function is called.
- Explanation: In the global context,
this
refers to the global object (window
in browsers). Inside a method,this
refers to the object that owns the method.
15. What are Prototypes in JavaScript?
Every JavaScript object has a prototype, which is also an object. All JavaScript objects inherit their properties and methods from their prototype.
- Explanation: Prototypes allow for inheritance, where properties or methods defined in a prototype can be shared across all instances of a particular object.
Conclusion
These 15 questions offer a solid starting point for your JavaScript interview preparation. In the actual guide, we will cover 35 more questions that focus on advanced topics like closures, event bubbling, performance optimization, module systems, and many more. This guide is designed to provide you with the understanding and confidence needed to excel in any JavaScript interview in 2024. Keep practicing, and you’ll be well-prepared for success!
16. What is the purpose of the bind()
, call()
, and apply()
methods in JavaScript?
These methods allow you to explicitly set the value of this
in a function:
bind()
: Returns a new function with a specifiedthis
value and optional arguments.call()
: Invokes a function with a giventhis
value and arguments passed individually.apply()
: Invokes a function with a giventhis
value and arguments passed as an array.- Example:
const person = {
name: "John",
greet: function() {
console.log(`Hello, ${this.name}`);
}
};
const anotherPerson = { name: "Jane" };
person.greet.call(anotherPerson); // Output: Hello, Jane
- Explanation: These methods are particularly useful when you need to borrow methods from one object and apply them to another.
17. What is the instanceof
operator?
The instanceof
operator checks if an object is an instance of a specific constructor function.
- Example:
const arr = [1, 2, 3];
console.log(arr instanceof Array); // true
- Explanation: It checks the prototype chain and returns
true
if the object is derived from the specified constructor.
18. What is the difference between deep and shallow copies in JavaScript?
- Shallow Copy: Copies an object but only at the first level. Nested objects are not copied but referenced.
- Deep Copy: Recursively copies all levels of an object, including nested objects.
- Example (Shallow Copy):
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = Object.assign({}, obj1);
obj2.b.c = 5;
console.log(obj1.b.c); // 5 (changes in `obj2` affect `obj1`)
- Example (Deep Copy using JSON):
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = JSON.parse(JSON.stringify(obj1));
obj2.b.c = 5;
console.log(obj1.b.c); // 2 (independent copies)
- Explanation: Shallow copies can lead to unintended side effects when modifying nested objects. Deep copies are often necessary for large and complex objects.
19. What is a Promise Chain?
A promise chain is a sequence of then()
methods chained together, where each subsequent then()
is executed after the previous one completes.
- Example:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log(data);
return fetch('https://api.example.com/moreData');
})
.then(moreData => console.log(moreData))
.catch(error => console.error(error));
- Explanation: Chaining promises makes handling asynchronous tasks easier by avoiding callback hell and making code more readable.
20. What is Event Bubbling and Capturing in JavaScript?
- Event Bubbling: When an event occurs on an element, it first triggers on the target element and then bubbles up to its parent elements.
- Event Capturing: The event is captured from the root element and travels down to the target element.
- Explanation: Bubbling is the default behavior, but you can control the event flow by setting the third parameter of
addEventListener()
totrue
for capturing.
21. What are Default Parameters in JavaScript?
Default parameters allow you to specify default values for function parameters if no argument is passed.
- Example:
function greet(name = "Guest") {
console.log(`Hello, ${name}!`);
}
greet(); // Output: Hello, Guest!
- Explanation: Default parameters simplify function calls when optional arguments are not provided.
22. What is the Spread Operator in JavaScript?
The spread operator (...
) allows an iterable such as an array to be expanded into individual elements.
- Example:
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // [1, 2, 3, 4, 5]
- Explanation: The spread operator is useful for array concatenation, copying objects, or passing multiple arguments to functions.
23. What are JavaScript Modules, and why are they important?
JavaScript modules allow you to break down your code into smaller, reusable pieces. They help in organizing code and avoiding the problem of global variables.
- Explanation: With ES6, you can use the
import
andexport
syntax to share code between files, leading to better maintainability and avoiding global namespace pollution.
24. What is NaN
in JavaScript, and how do you check for it?
NaN
stands for Not-A-Number and occurs when a mathematical operation fails to produce a meaningful result.
- Example:
console.log(isNaN("abc" * 2)); // true
- Explanation: You can check if a value is
NaN
usingisNaN()
or by comparing it withNumber.isNaN()
for more strict type checking.
25. What is the difference between map()
, filter()
, and reduce()
?
map()
: Transforms each element in an array and returns a new array.filter()
: Filters elements based on a condition and returns a new array.reduce()
: Reduces the array to a single value based on a reducer function.- Example:
const arr = [1, 2, 3, 4];
const doubled = arr.map(x => x * 2); // [2, 4, 6, 8]
const even = arr.filter(x => x % 2 === 0); // [2, 4]
const sum = arr.reduce((acc, curr) => acc + curr, 0); // 10
- Explanation: These methods are crucial in functional programming, simplifying array manipulations and reducing boilerplate code.
26. What are IIFEs (Immediately Invoked Function Expressions)?
An IIFE is a function that is executed immediately after it is defined.
- Example:
(function() {
console.log("This is an IIFE");
})();
- Explanation: IIFEs are useful for creating local scopes and avoiding global variable pollution.
27. What are Template Literals in JavaScript?
Template literals are strings that allow embedded expressions and multi-line strings using backticks (`
).
- Example:
const name = "John";
const greeting = `Hello, ${name}!`;
console.log(greeting); // Hello, John!
- Explanation: Template literals make string interpolation and formatting much simpler compared to concatenation with
+
.
28. What is the use of the async
keyword in JavaScript?
The async
keyword is used to declare asynchronous functions, which return a Promise
.
- Explanation: It enables you to use
await
inside the function to pause execution until a promise is resolved, making asynchronous code more readable and easier to maintain.
29. What is a Callback Function?
A callback function is a function passed as an argument to another function, to be executed after a certain event or task.
- Example:
function fetchData(callback) {
setTimeout(() => {
callback("Data loaded");
}, 1000);
}
fetchData(data => console.log(data)); // Data loaded
- Explanation: Callbacks are a way of handling asynchronous tasks, although they can lead to callback hell when nesting multiple functions.
30. What is the difference between synchronous and asynchronous code in JavaScript?
- Synchronous Code: Executes line by line and waits for each operation to complete.
- Asynchronous Code: Executes without blocking the main thread, allowing other tasks to run while waiting for an operation to finish.
- Explanation: Asynchronous code is essential for web applications that need to handle I/O operations like network requests or file system operations without freezing the user interface.
31. What is Destructuring in JavaScript?
Destructuring is a syntax that allows you to extract values from arrays or objects into variables.
- Example:
const [a, b] = [1, 2];
const { name, age } = { name: "John", age: 25 };
- Explanation: Destructuring simplifies the extraction of values, making code more concise and readable.
32. What are Symbols in JavaScript?
Symbols are a unique and immutable primitive data type introduced in ES6, often used for object property keys to avoid naming collisions.
- Example:
const sym = Symbol("unique");
const obj = { [sym]: "value" };
console.log(obj[sym]); // value
- Explanation: Symbols are useful in scenarios where you need to create unique identifiers, especially in large-scale applications or libraries.
33. What is the difference between setTimeout()
and setInterval()
?
setTimeout()
: Executes a function once after a specified delay.setInterval()
: Repeatedly executes a function at specified intervals.- Example:
setTimeout(() => console.log("Executed after 2 seconds"), 2000);
setInterval(() => console.log("Executed every 2 seconds"), 2000);
- Explanation: Both methods are used for handling timed events, but
setInterval()
continues executing until cleared, whilesetTimeout()
only runs once.
34. What is the debounce
technique in JavaScript?
Debouncing is a technique to limit the number of times a function is invoked over time. It ensures the function is executed after a certain delay once the event stops firing.
- Example:
function debounce(func, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, args), delay);
};
}
- Explanation: This is often used in scenarios like form validation or search boxes, where frequent input events can lead to performance issues.
35. What is the throttle
technique in JavaScript?
Throttling ensures that a function is called at most once in a specified time interval, regardless of how many times the event occurs.
- Example:
function throttle(func, delay) {
let lastCall = 0;
return function(...args) {
const now = new Date().getTime();
if (now - lastCall >= delay) {
lastCall = now;
func.apply(this, args);
}
};
}
- Explanation: Throttling is useful in scenarios like window resizing or scrolling, where you want to limit the frequency of function calls.
36. What is the use of 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.
- Example:
function Person(name, age) {
this.name = name;
this.age = age;
}
const john = new Person("John", 30);
console.log(john.name); // Output: John
- Explanation: When you use
new
, it creates a new object, sets the constructor’sthis
to the new object, and returns the object, allowing for object-oriented behavior in JavaScript.
37. What is Function Currying in JavaScript?
Currying is the process of transforming a function that takes multiple arguments into a sequence of functions, each taking a single argument.
- Example:
function add(x) {
return function(y) {
return x + y;
}
}
const add5 = add(5);
console.log(add5(3)); // Output: 8
- Explanation: Currying is a functional programming technique that allows for partial application of functions, meaning you can fix some arguments and pass others later.
38. What is the difference between forEach()
and map()
in JavaScript?
forEach()
: Executes a provided function once for each array element, but does not return anything.map()
: Executes a provided function for each array element and returns a new array with the results.- Example:
const arr = [1, 2, 3];
arr.forEach(x => console.log(x * 2)); // 2, 4, 6
const doubled = arr.map(x => x * 2);
console.log(doubled); // [2, 4, 6]
- Explanation: Use
map()
when you need to transform an array and return the results, whileforEach()
is better for executing side effects like logging or modifying external variables.
39. What are Generators in JavaScript?
Generators are functions that can be paused and resumed, allowing you to control the execution flow. They are defined using the function*
syntax and yield values using the yield
keyword.
- Example:
function* generatorFunction() {
yield 1;
yield 2;
yield 3;
}
const gen = generatorFunction();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
- Explanation: Generators are used for lazy evaluation, making them useful in scenarios like infinite sequences or iterating over large datasets efficiently.
40. What are WeakMap and WeakSet in JavaScript?
WeakMap
: A collection of key-value pairs where the keys are objects and the values can be arbitrary data. The references to keys are weak, meaning the garbage collector can remove them if there are no other references.WeakSet
: A collection of unique objects, also with weak references, meaning objects in aWeakSet
can be garbage collected.- Explanation: WeakMap and WeakSet are useful when you need to manage memory efficiently, especially in cases where you want objects to be garbage-collected as soon as they are no longer referenced elsewhere.
41. What are the different ways to create objects in JavaScript?
- Object Literal:
const obj = { name: "John", age: 30 };
- Constructor Function:
function Person(name, age) { this.name = name; this.age = age; } const person = new Person("John", 30);
- Object.create():
const obj = Object.create(null);
- ES6 Class:
class Person { constructor(name, age) { this.name = name; this.age = age; } } const person = new Person("John", 30);
- Explanation: These methods allow flexibility in creating objects, depending on the complexity of the object and the requirements of your project.
42. What is Strict Mode in JavaScript, and how can it be enabled?
Strict mode is a way to opt into a restricted variant of JavaScript, which helps catch common coding mistakes and “unsafe” actions, such as defining global variables unintentionally.
- How to enable:
"use strict";
- Explanation: Strict mode is useful for writing cleaner code and avoiding common pitfalls, such as silent errors or undeclared variables.
43. What is an Immediately Resolved Promise?
An immediately resolved promise is a promise that is resolved immediately with a value. This can be useful in situations where you want to simulate asynchronous behavior or return a resolved value.
- Example:
Promise.resolve('Resolved!').then(value => console.log(value)); // Output: Resolved!
- Explanation:
Promise.resolve()
creates a promise that is already resolved with a given value, making it helpful in cases where you need to wrap a value in a promise.
44. What is Object.freeze()
in JavaScript?
Object.freeze()
is used to freeze an object, preventing any changes to its properties or values. The object becomes immutable.
- Example:
const obj = { name: "John" };
Object.freeze(obj);
obj.name = "Jane"; // Error in strict mode, or silently ignored
console.log(obj.name); // Output: John
- Explanation:
Object.freeze()
is useful in situations where you need to ensure that the object’s structure and data remain unchanged throughout the lifecycle of the program.
45. What is Polyfill in JavaScript?
A polyfill is code that provides modern functionality on older browsers that do not support it natively.
- Example: If the
Array.prototype.includes()
method is not supported in older browsers, a polyfill can be written as:
if (!Array.prototype.includes) {
Array.prototype.includes = function(item) {
return this.indexOf(item) !== -1;
};
}
- Explanation: Polyfills allow developers to write modern JavaScript code while ensuring compatibility with older browsers.
46. What is Object.assign()
and what are its use cases?
Object.assign()
is used to copy properties from one or more source objects to a target object. It returns the modified target object.
- Example:
const target = { a: 1 };
const source = { b: 2, c: 3 };
Object.assign(target, source);
console.log(target); // { a: 1, b: 2, c: 3 }
- Explanation:
Object.assign()
is useful for shallow cloning objects or merging multiple objects into one.
47. What is the difference between Object.seal()
and Object.freeze()
?
Object.seal()
: Prevents new properties from being added to an object, but allows modification of existing properties.Object.freeze()
: Prevents new properties from being added and prevents modification of existing properties.- Explanation: Use
Object.seal()
when you want to protect the object’s structure but still allow updates to its values. UseObject.freeze()
when you want to completely lock down the object.
48. What are JavaScript Decorators?
Decorators are a proposal (in stage 3 as of 2024) that allow you to modify the behavior of classes or methods. They are functions that can be applied to methods, properties, or classes.
- Example:
function readonly(target, key, descriptor) {
descriptor.writable = false;
return descriptor;
}
class Example {
@readonly
method() {
console.log("This is a read-only method.");
}
}
- Explanation: Decorators allow you to extend the functionality of classes or methods without modifying the original code.
49. What is Optional Chaining (?.
) in JavaScript?
Optional chaining allows you to safely access deeply nested properties without checking if each reference in the chain is null
or undefined
.
- Example:
const user = { name: "John", address: { city: "New York" } };
console.log(user.address?.city); // Output: New York
console.log(user.address?.postalCode); // Output: undefined
- Explanation: This prevents runtime errors when trying to access properties on
null
orundefined
objects, making code safer and more readable.
50. What is the difference between import
and require()
?
import
: ES6 module syntax that allows you to import specific exports from a module. It’s statically analyzed, meaning it’s evaluated at compile time.require()
: CommonJS module syntax that imports the entire module dynamically at runtime.- Example:
import { myFunction } from './module'; // ES6
const myFunction = require('./module'); // CommonJS
- Explanation:
import
is the modern module system used in ES6 and beyond, whilerequire()
is still common in Node.js for older codebases.
51. What is Debouncing in JavaScript?
Debouncing is a programming pattern used to ensure that a time-consuming function does not fire too often. It limits the rate at which a function is executed by delaying the function execution until a certain amount of time has passed since the last time it was invoked.
- Example:
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
const log = debounce(() => console.log("Debounced!"), 1000);
window.addEventListener('resize', log);
- Explanation: In the example, the
log
function will only be called once the user has stopped resizing the window for 1 second.
52. What is Throttling in JavaScript?
Throttling is a technique to ensure a function is called at most once during a specified period. It’s useful in cases where events can fire very frequently, such as scrolling or resizing.
- Example:
function throttle(func, delay) {
let lastCall = 0;
return function(...args) {
const now = new Date().getTime();
if (now - lastCall >= delay) {
lastCall = now;
func.apply(this, args);
}
};
}
const log = throttle(() => console.log("Throttled!"), 1000);
window.addEventListener('scroll', log);
- Explanation: In the example, the
log
function will be triggered once every second as the user scrolls, regardless of how frequently the scroll event fires.
53. What is the difference between LocalStorage, SessionStorage, and Cookies?
- LocalStorage: Stores data with no expiration date. Data persists even after the browser is closed.
- SessionStorage: Stores data only for the duration of the page session. Data is lost when the page or browser is closed.
- Cookies: Can store data that persists even after the browser is closed, with an expiration date.
- Example:
// LocalStorage
localStorage.setItem('key', 'value');
console.log(localStorage.getItem('key')); // value
// SessionStorage
sessionStorage.setItem('key', 'value');
console.log(sessionStorage.getItem('key')); // value
// Cookies
document.cookie = "username=John; expires=Fri, 31 Dec 2024 12:00:00 UTC;";
- Explanation: LocalStorage and SessionStorage are part of the Web Storage API and have a larger storage capacity than cookies, which are typically used for managing user sessions.
54. What is the this
keyword in JavaScript?
The this
keyword refers to the object it belongs to, and its value depends on how a function is called.
- In a method:
this
refers to the object that owns the method. - Alone:
this
refers to the global object. - In a function:
this
refers to the global object (in non-strict mode) orundefined
(in strict mode). - In an event:
this
refers to the element that received the event. - Example:
const obj = {
name: 'John',
greet: function() {
console.log(this.name); // "John"
}
};
obj.greet();
function show() {
console.log(this); // In strict mode: undefined; otherwise, the global object (window in browsers)
}
- Explanation: Understanding how
this
works is key to avoiding errors in JavaScript, especially in object-oriented and event-driven programming.
55. What is call()
, apply()
, and bind()
in JavaScript?
These methods are used to explicitly set the value of this
when calling a function:
call()
: Invokes a function with a specifiedthis
value and individual arguments.apply()
: Similar tocall()
, but takes an array of arguments.bind()
: Returns a new function wherethis
is permanently bound to the provided value.- Example:
const person = { name: 'John' };
function greet(greeting) {
console.log(`${greeting}, ${this.name}`);
}
greet.call(person, 'Hello'); // "Hello, John"
greet.apply(person, ['Hi']); // "Hi, John"
const greetPerson = greet.bind(person);
greetPerson('Hey'); // "Hey, John"
- Explanation:
call()
,apply()
, andbind()
are essential for controlling the execution context in situations wherethis
needs to be explicitly defined.
56. What are Template Literals in JavaScript?
Template literals allow embedded expressions in strings using backticks (`
) rather than quotes.
- Example:
const name = 'John';
const greeting = `Hello, ${name}!`;
console.log(greeting); // "Hello, John!"
- Explanation: Template literals provide cleaner syntax for string interpolation, allowing multiline strings and embedded expressions.
57. What are Tagged Template Literals in JavaScript?
Tagged template literals allow you to parse template literals with a function. The function can process the text and the values of the placeholders.
- Example:
function tag(strings, ...values) {
return strings[0] + values.map(value => value.toUpperCase()).join('');
}
const result = tag`Hello, ${'John'}!`;
console.log(result); // "Hello, JOHN!"
- Explanation: Tagged templates allow you to create specialized string-processing functions, such as for localization or HTML escaping.
58. What is the fetch()
API?
The fetch()
API provides a modern and easy way to make HTTP requests in JavaScript. It returns a promise that resolves to the Response
object.
- Example:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
- Explanation: The
fetch()
API simplifies the process of sending network requests compared to older methods likeXMLHttpRequest
.
59. What is an IIFE (Immediately Invoked Function Expression)?
An IIFE is a function that is executed immediately after it is defined. It’s often used to avoid polluting the global scope.
- Example:
(function() {
console.log('IIFE executed');
})();
- Explanation: IIFEs create a local scope and immediately execute the function. This pattern is useful for avoiding global variables.
60. What are Promises in JavaScript?
A Promise is an object representing the eventual completion or failure of an asynchronous operation. A promise can be in one of three states: pending, fulfilled, or rejected.
- Example:
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('Success!'), 1000);
});
promise.then(result => console.log(result));
- Explanation: Promises are crucial for handling asynchronous operations and preventing callback hell in modern JavaScript.
61. What is the difference between setTimeout()
and setInterval()
?
setTimeout()
: Executes a function once after a specified delay.setInterval()
: Executes a function repeatedly at specified intervals.- Example:
setTimeout(() => console.log('This runs once after 2 seconds'), 2000);
const intervalId = setInterval(() => console.log('This runs every 2 seconds'), 2000);
clearInterval(intervalId); // Stops the interval
- Explanation:
setTimeout()
is useful for delaying execution, whilesetInterval()
is used for repeating a function at regular intervals.
62. What are JavaScript Data Types?
JavaScript has the following primitive data types:
- String: A sequence of characters.
- Number: Numeric data, including integers and floating points.
- Boolean: Represents
true
orfalse
. - Null: An intentional absence of value.
- Undefined: A variable that has been declared but not assigned a value.
- Symbol: A unique and immutable data type (introduced in ES6).
- BigInt: A large integer type (introduced in ES2020).
- Example:
let name = 'John'; // String
let age = 30; // Number
let isActive = true; // Boolean
let score = null; // Null
let value; // Undefined
let id = Symbol('id'); // Symbol
let bigIntValue = BigInt(9007199254740991); // BigInt
- Explanation: JavaScript’s primitive data types form the foundation of working with variables and values in the language.
63. What is the difference between Mutable and Immutable data types in JavaScript?
- Mutable data types: Can be modified after they are created (e.g., objects, arrays).
- Immutable data types: Cannot be changed once created (e.g., strings, numbers, booleans).
- Example:
const obj = { name: 'John' };
obj.name = 'Jane'; // Mutable object
const str = 'Hello';
str[0] = 'h'; // Immutable string (this doesn't change the string)
console.log(str); // "Hello"
- Explanation: Knowing which data types are mutable and immutable helps developers write predictable and efficient code.
64. What is the typeof
operator in JavaScript?
The typeof
operator is used to determine the type of a variable or value.
- Example:
console.log(typeof 123); // "number"
console.log(typeof 'Hello'); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof { name: 'John' }); // "object"
console.log(typeof null); // "object" (this is considered a bug in JavaScript)
- Explanation:
typeof
is a fundamental tool for checking data types, though it has some inconsistencies (e.g.,null
being reported as an object).
65. What are Prototypes in JavaScript?
In JavaScript, every object has a prototype. A prototype is an object from which other objects inherit properties and methods.
- Example:
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, ${this.name}`);
};
const john = new Person('John');
john.greet(); // Output: "Hello, John"
- Explanation: Prototypes are central to JavaScript’s inheritance model, allowing objects to share methods and properties without duplicating them across instances.
66. What is Function Composition in JavaScript?
Function composition is a technique where you combine two or more functions to create a new function. The result of one function is passed as input to the next.
- Example:
const add = (x) => x + 1;
const multiply = (x) => x * 2;
const compose = (f, g) => (x) => f(g(x));
const addThenMultiply = compose(multiply, add);
console.log(addThenMultiply(5)); // Output: 12
- Explanation: Function composition is useful in functional programming for creating more complex functions by combining simpler ones.
67. What is the super
keyword in JavaScript?
The super
keyword is used to call the constructor of a parent class in subclasses. It also allows access to parent class methods.
- Example:
class Parent {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello from ${this.name}`);
}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
introduce() {
super.greet();
console.log(`I am ${this.age} years old.`);
}
}
const child = new Child('John', 25);
child.introduce();
- Explanation: The
super
keyword helps in extending functionality from parent classes while adding or overriding methods in child classes.
68. What is the difference between splice()
and slice()
in JavaScript?
splice()
: Modifies the original array by removing or adding elements.slice()
: Returns a shallow copy of a portion of an array without modifying the original array.- Example:
const arr = [1, 2, 3, 4, 5];
const spliced = arr.splice(1, 2); // Modifies original array
console.log(arr); // [1, 4, 5]
const sliced = arr.slice(1, 3); // Does not modify original array
console.log(sliced); // [4, 5]
- Explanation:
splice()
is used when you need to modify an array in place, whileslice()
is used for creating a copy of a subset of the array.
69. What is Event Propagation in JavaScript?
Event propagation describes the flow of events through the DOM, which occurs in three phases:
- Capturing Phase: The event is first captured from the root element down to the target element.
- Target Phase: The event reaches the target element.
- Bubbling Phase: The event bubbles up from the target element to the root.
- Example:
document.querySelector("#child").addEventListener("click", () => console.log("Child clicked!"));
document.querySelector("#parent").addEventListener("click", () => console.log("Parent clicked!"));
- Explanation: Event propagation can be controlled by using event methods like
stopPropagation()
to prevent bubbling or capturing phases.
70. What is the difference between Object.keys()
, Object.values()
, and Object.entries()
?
Object.keys()
: Returns an array of an object’s property names.Object.values()
: Returns an array of an object’s property values.Object.entries()
: Returns an array of an object’s key-value pairs as arrays.- Example:
const obj = { name: 'John', age: 25 };
console.log(Object.keys(obj)); // ["name", "age"]
console.log(Object.values(obj)); // ["John", 25]
console.log(Object.entries(obj)); // [["name", "John"], ["age", 25]]
- Explanation: These methods are useful for iterating over an object’s properties and values in various ways.
71. What are the different types of Scopes in JavaScript?
JavaScript has the following types of scope:
- Global Scope: Variables declared outside any function are accessible from anywhere in the code.
- Function Scope: Variables declared inside a function are only accessible within that function.
- Block Scope: Variables declared inside a block (
{}
) usinglet
orconst
are only accessible within that block. - Example:
let globalVar = "I'm global";
function myFunction() {
let functionVar = "I'm in a function";
if (true) {
let blockVar = "I'm in a block";
console.log(blockVar); // Accessible here
}
console.log(functionVar); // Accessible here
// console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined
}
myFunction();
- Explanation: Understanding scope is essential for managing variables effectively and preventing accidental variable collisions.
72. What is the WeakRef
in JavaScript?
A WeakRef
is a weak reference to an object, meaning the object can still be garbage-collected if there are no other strong references to it. WeakRef
was introduced in ECMAScript 2021.
- Example:
let obj = { name: "John" };
let weakRef = new WeakRef(obj);
obj = null; // Object is eligible for garbage collection
console.log(weakRef.deref()); // May return undefined if the object is collected
- Explanation:
WeakRef
is used in scenarios where you need to refer to an object without preventing it from being garbage-collected, such as in caching mechanisms.
73. What is a Proxy in JavaScript?
A Proxy
object allows you to define custom behavior for fundamental operations on objects (e.g., property access, assignment, function calls).
- Example:
const target = {
name: 'John'
};
const handler = {
get: (obj, prop) => {
return prop in obj ? obj[prop] : `Property ${prop} does not exist.`;
}
};
const proxy = new Proxy(target, handler);
console.log(proxy.name); // John
console.log(proxy.age); // Property age does not exist.
- Explanation: Proxies are useful for tasks like validation, formatting, or default behavior when working with objects.
74. What is the Symbol.iterator
in JavaScript?
The Symbol.iterator
is a well-known symbol used to define the default iterator for an object, allowing it to be iterated over using for...of
loops.
- Example:
const myIterable = {
data: [1, 2, 3],
[Symbol.iterator]() {
let index = 0;
return {
next: () => ({
value: this.data[index++],
done: index > this.data.length
})
};
}
};
for (let value of myIterable) {
console.log(value); // 1, 2, 3
}
- Explanation: Defining a custom
Symbol.iterator
allows you to make objects iterable and use them with constructs likefor...of
and the spread operator.
75. What are JavaScript Iterators and Generators?
- Iterators: An object that implements the
next()
method, which returns an object with two properties:value
anddone
. - Generators: Functions that can be paused and resumed using the
yield
keyword. - Example (Iterator):
const iterator = {
data: [1, 2, 3],
index: 0,
next() {
return this.index < this.data.length
? { value: this.data[this.index++], done: false }
: { done: true };
}
};
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
- Example (Generator):
function* generator() {
yield 1;
yield 2;
yield 3;
}
const gen = generator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
- Explanation: Iterators and generators enable efficient handling of sequences of data, making it easier to work with large or potentially infinite datasets.
76. What is Object Destructuring in JavaScript?
Object destructuring allows you to unpack values from objects and assign them to variables.
- Example:
const person = { name: 'John', age: 25 };
const { name, age } = person;
console.log(name); // John
console.log(age); // 25
- Explanation: Destructuring is a convenient way to extract data from objects or arrays and assign them to variables in one line.
77. What is Array Destructuring in JavaScript?
Array destructuring allows you to unpack values from arrays and assign them to variables.
- Example:
const arr = [1, 2, 3];
const [first, second, third] = arr;
console.log(first); // 1
console.log(second); // 2
console.log(third); // 3
- Explanation: Array destructuring simplifies extracting values from arrays, especially when working with multiple variables.
78. What is Optional Chaining (?.
) in JavaScript?
Optional chaining allows you to access deeply nested properties of an object without having to check if each reference in the chain is null or undefined.
- Example:
const user = { name: 'John', address: { city: 'New York' } };
console.log(user.address?.city); // New York
console.log(user.address?.postalCode); // undefined (no error)
- Explanation: Optional chaining prevents runtime errors when trying to access properties that may not exist on an object.
79. What is Nullish Coalescing (??
) in JavaScript?
The nullish coalescing operator (??
) returns the right-hand operand if the left-hand operand is null
or undefined
; otherwise, it returns the left-hand operand.
- Example:
let value = null;
console.log(value ?? 'Default'); // Output: Default
value = 0;
console.log(value ?? 'Default'); // Output: 0
- Explanation: Nullish coalescing is useful for setting default values without overriding falsy values like
0
orfalse
.
80. What are Set
and Map
in JavaScript?
Set
: A collection of unique values.Map
: A collection of key-value pairs where keys can be any data type.- Example (
Set
):
const set = new Set([1, 2, 2, 3]);
console.log(set); // Set { 1, 2, 3 }
- Example (
Map
):
const map = new Map();
map.set('name', 'John');
map.set('age', 25);
console.log(map.get('name')); // John
- Explanation:
Set
andMap
are useful for working with collections of unique values and key-value pairs, respectively, and offer more flexibility than arrays and objects for specific use cases.
81. What is the purpose of Object.getOwnPropertyDescriptors()
in JavaScript?
Object.getOwnPropertyDescriptors()
returns all own property descriptors of an object. A property descriptor is an object that holds details about a property, such as its value, whether it’s writable, enumerable, or configurable.
- Example:
const obj = {
name: "John",
age: 30
};
const descriptors = Object.getOwnPropertyDescriptors(obj);
console.log(descriptors);
- Explanation: This method is useful when you need to clone an object along with its property descriptors (e.g., in creating deep clones or implementing proxy patterns).
82. What is the difference between Object.preventExtensions()
, Object.seal()
, and Object.freeze()
?
Object.preventExtensions()
: Prevents new properties from being added to an object.Object.seal()
: Prevents adding or removing properties but allows modifying existing ones.Object.freeze()
: Prevents adding, removing, or modifying properties.- Example:
const obj = { name: 'John' };
Object.preventExtensions(obj);
Object.seal(obj);
Object.freeze(obj);
- Explanation: These methods provide varying levels of control over object mutability, allowing you to safeguard data in different ways.
83. What is the Reflect
API in JavaScript?
The Reflect
object provides methods for interceptable JavaScript operations. It is similar to the Object
object but more focused on low-level operations.
- Example:
const obj = { name: 'John' };
Reflect.set(obj, 'age', 25);
console.log(Reflect.get(obj, 'age')); // 25
- Explanation:
Reflect
is often used in combination withProxy
for performing meta-operations and better managing object manipulations.
84. What is the purpose of Function.prototype.call()
and how does it differ from Function.prototype.apply()
?
call()
: Calls a function with a specificthis
value and arguments passed individually.apply()
: Calls a function with a specificthis
value and arguments passed as an array.- Example:
function greet(greeting, name) {
console.log(`${greeting}, ${name}`);
}
greet.call(null, 'Hello', 'John'); // Hello, John
greet.apply(null, ['Hi', 'Jane']); // Hi, Jane
- Explanation:
call()
is used when you have individual arguments, whereasapply()
is useful when arguments are already in an array or array-like format.
85. What are the differences between Object.create()
and the new
keyword?
Object.create()
: Creates a new object with a specified prototype and optional property descriptors.new
keyword: Creates an instance of a constructor function or class.- Example (
Object.create()
):
const person = {
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
const john = Object.create(person);
john.name = 'John';
john.greet(); // Hello, my name is John
- Explanation:
Object.create()
is more flexible, as it allows setting the prototype explicitly, whilenew
is tied to constructor functions or classes.
86. What is the in
operator in JavaScript?
The in
operator checks whether a property exists in an object, either directly or in its prototype chain.
- Example:
const obj = { name: 'John' };
console.log('name' in obj); // true
console.log('toString' in obj); // true (inherited from Object.prototype)
- Explanation: The
in
operator is useful for checking property existence, even when the property is inherited through the prototype chain.
87. What are JavaScript Symbols, and how are they used?
Symbols are unique and immutable primitive values introduced in ES6. They are often used as unique property keys.
- Example:
const sym = Symbol('id');
const obj = {
[sym]: '12345'
};
console.log(obj[sym]); // 12345
- Explanation: Symbols allow you to create hidden object properties that are not visible during enumeration, useful for internal properties or APIs.
88. What is the difference between isNaN()
and Number.isNaN()
?
isNaN()
: Converts the argument to a number and then checks if it isNaN
.Number.isNaN()
: Strictly checks if the value isNaN
without type coercion.- Example:
console.log(isNaN('Hello')); // true (because 'Hello' is coerced to NaN)
console.log(Number.isNaN('Hello')); // false (no coercion)
- Explanation:
Number.isNaN()
is the preferred method for checkingNaN
in modern JavaScript, as it avoids type coercion.
89. What is the instanceof
operator in JavaScript?
The instanceof
operator checks if an object is an instance of a constructor or if it inherits from that constructor’s prototype.
- Example:
function Person() {}
const john = new Person();
console.log(john instanceof Person); // true
- Explanation:
instanceof
is used to determine the prototype chain relationship between objects and constructors.
90. What is JSON, and how is it used in JavaScript?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is commonly used for sending and receiving data in web applications.
- Example:
const jsonString = '{"name": "John", "age": 30}';
const obj = JSON.parse(jsonString); // Converts JSON string to JavaScript object
console.log(obj.name); // John
const newJsonString = JSON.stringify(obj); // Converts JavaScript object to JSON string
- Explanation: JSON is used to serialize and deserialize data for communication between the client and server, typically in REST APIs.
91. What is memoization in JavaScript?
Memoization is an optimization technique that stores the results of expensive function calls and returns the cached result when the same inputs occur again.
- Example:
function memoize(fn) {
const cache = {};
return function(...args) {
const key = args.toString();
if (cache[key]) return cache[key];
const result = fn(...args);
cache[key] = result;
return result;
};
}
const add = (a, b) => a + b;
const memoizedAdd = memoize(add);
console.log(memoizedAdd(1, 2)); // 3 (calculated)
console.log(memoizedAdd(1, 2)); // 3 (cached)
- Explanation: Memoization improves performance by avoiding repeated calculations for the same inputs, which is useful in computationally heavy functions.
92. What is the difference between synchronous and asynchronous JavaScript?
- Synchronous JavaScript: Code runs line by line, and each line waits for the previous one to finish before continuing.
- Asynchronous JavaScript: Code allows other operations to run in parallel while waiting for a task to complete, often using callbacks, promises, or async/await.
- Example (Synchronous):
console.log('Start');
console.log('End');
// Output: Start, End
- Example (Asynchronous using setTimeout):
console.log('Start');
setTimeout(() => console.log('Delayed'), 1000);
console.log('End');
// Output: Start, End, Delayed
- Explanation: Asynchronous code is crucial for tasks like API calls, file operations, or timers without blocking the main thread.
93. What is the difference between synchronous and asynchronous functions in JavaScript?
- Synchronous functions: Execute code sequentially, one after another.
- Asynchronous functions: Allow code execution to continue without waiting for the function to finish.
- Example (Synchronous):
function syncFunc() {
console.log('Sync Function Start');
console.log('Sync Function End');
}
syncFunc();
- Example (Asynchronous with setTimeout):
function asyncFunc() {
console.log('Async Function Start');
setTimeout(() => console.log('Async Function End'), 1000);
}
asyncFunc();
- Explanation: Asynchronous functions are essential for handling tasks that require waiting, such as network requests or reading files, without freezing the user interface.
94. What is the Event Loop in JavaScript?
The Event Loop is a mechanism in JavaScript that handles asynchronous code execution by pushing callback functions from the queue into the call stack when the stack is empty.
- Explanation: JavaScript is single-threaded, but the Event Loop allows it to handle asynchronous operations like timers, I/O events, and promises by processing callbacks and tasks when the main execution thread is free.
95. What are Web Workers in JavaScript?
Web Workers provide a way to run JavaScript in background threads. They do not block the main thread, allowing you to run expensive tasks without affecting the user interface.
- Example:
// main.js
const worker = new Worker('worker.js');
worker.postMessage('Start task');
worker.onmessage = (event) => {
console.log(`Received from worker: ${event.data}`);
};
// worker.js
self.onmessage = (event) => {
console.log(event.data); // Start task
self.postMessage('Task finished');
};
- Explanation: Web Workers are useful for performing computationally heavy tasks like data processing or handling large files in the background, ensuring that the main UI remains responsive.
96. What is lazy loading in JavaScript?
Lazy loading is a performance optimization technique that delays the loading of resources (such as images, scripts, or components) until they are needed.
- Example:
<img src="image.jpg" loading="lazy" alt="Lazy loaded image">
- Explanation: Lazy loading improves page load time by only loading resources when they are about to be displayed, reducing initial page load overhead.
97. What is the purpose of Object.fromEntries()
in JavaScript?
Object.fromEntries()
transforms a list of key-value pairs into an object. It is the reverse operation of Object.entries()
.
- Example:
const entries = [['name', 'John'], ['age', 30]];
const obj = Object.fromEntries(entries);
console.log(obj); // { name: 'John', age: 30 }
- Explanation:
Object.fromEntries()
is useful when working with key-value pairs that need to be transformed into an object, such as after usingObject.entries()
for object manipulation.