Here’s a comprehensive list of 100 JavaScript interview questions along with answers, covering a wide range of topics from basic concepts to advanced features. This list should be very useful for interview preparation.
Basic JavaScript Questions
- What is JavaScript?
– Answer: JavaScript is a scripting language used to create and control dynamic content on websites, like interactive forms, animations, and games. - How do you declare a variable in JavaScript?
– Answer: Using var, let, or const.
Example: let name = “John”; - What is the difference between let, const, and var?
– Answer: var is function-scoped, while let and const are block-scoped. const cannot be reassigned after its initial assignment. - What are data types in JavaScript?
– Answer: Primitive types: string, number, boolean, null, undefined, symbol, bigint.
Reference types: objects, arrays, functions. - What is the typeof operator in JavaScript?
– Answer: The typeof operator returns the type of a variable or expression.
– Example: typeof 42 returns “number”. - What is null and undefined?
– Answer: null is an assignment value representing no value. undefined means a variable has been declared but not assigned a value. - What are JavaScript functions?
– Answer:Functions are reusable blocks of code that perform a specific task.
– Example:
function greet() {
console.log(“Hello!”);
} - What is a callback function?
– Answer: A callback is a function passed into another function as an argument, which is then invoked inside the outer function. - What is an array in JavaScript?
– Answer: An array is a data structure that holds a list of values, which can be of any type.
– Example: let colors = [“red”, “green”, “blue”]; - What is a JavaScript object?
– Answer:Objects are collections of key-value pairs, where each key is associated with a value.
– Example:
let car = {
make: “Toyota”,
model: “Corolla”,
year: 2020
}; - How do you access object properties?
– Answer: Using dot notation or bracket notation.
– Example: car.make or car[“make”]. - What is the difference between == and ===?
– Answer: == checks for value equality with type coercion, while === checks for both value and type equality. - Explain the concept of scope in JavaScript.
– Answer: Scope determines the accessibility of variables and functions. JavaScript has function scope and block scope (with let and const). - What is hoisting in JavaScript?
– Answer: Hoisting is JavaScript’s default behavior of moving declarations to the top of the current scope before code execution. - What is the difference between let and var in terms of hoisting?
– Answer: var is hoisted to the top and initialized as undefined. let is hoisted but not initialized, leading to a ReferenceError if accessed before initialization. - What are closures in JavaScript?
– Answer: Closures are functions that have access to their outer function’s scope even after the outer function has returned. - What is an IIFE (Immediately Invoked Function Expression)?
– Answer: An IIFE is a function that runs as soon as it is defined.
– Example:
(function() {
console.log(“IIFE!”);
})(); - What is the this keyword in JavaScript?
– Answer: this refers to the context in which the function is called. - How can you bind the value of this to a function?
– Answer: Using the bind(), call(), or apply() methods. - What is the difference between call(), apply(), and bind()?
– Answer: call() and apply() invoke a function with a specific this value and arguments. call() accepts arguments individually, while apply() accepts them as an array. bind() returns a new function, binding this to the provided value.
Intermediate JavaScript Questions
- What is event bubbling and event capturing?
– Answer:Event bubbling: Events propagate from the target element up through the DOM tree.
Event capturing: Events propagate from the root to the target element. - What is event delegation?
– Answer: Event delegation allows you to add a single event listener to a parent element that will fire for all its children, even if added dynamically. - What is a JavaScript promise?
– Answer: A promise is an object representing the eventual completion or failure of an asynchronous operation.
– Example:
let promise = new Promise((resolve, reject) => {
// async operation
}); - What are async and await in JavaScript?
– Answer: async functions return a promise, and await pauses the function execution until the promise resolves. - What is the event loop in JavaScript?
– Answer: The event loop allows JavaScript to perform non-blocking operations by offloading operations to the browser, and then picking up their results when they are ready. - What is the difference between synchronous and asynchronous code in JavaScript?
– Answer: Synchronous code is executed sequentially, blocking the code that follows until it is complete. Asynchronous code allows for non-blocking operations, so the program can continue executing. - What is JSON, and how do you parse it in JavaScript?
– Answer: JSON (JavaScript Object Notation) is a format for structuring data. It can be parsed using JSON.parse() and converted to a string with JSON.stringify(). - What is destructuring in JavaScript?
– Answer: Destructuring is a way to unpack values from arrays or properties from objects into distinct variables.
– Example:
let {name, age} = {name: “John”, age: 25}; - What is a higher-order function?
– Answer: A higher-order function is a function that takes another function as an argument or returns a function. - What are JavaScript modules?
– Answer: JavaScript modules are reusable pieces of code that can be imported and exported between files.
– Example:
// export
export const myFunc = () => {};
// import
import { myFunc } from ‘./myModule.js’;
- What is the spread operator in JavaScript?
– Answer: The spread operator (…) allows an iterable to expand in places where zero or more arguments or elements are expected.
– Example:
let arr1 = [1, 2];
let arr2 = […arr1, 3, 4]; // [1, 2, 3, 4] - What is the rest operator in JavaScript?
– Answer: The rest operator (…) allows you to represent an indefinite number of arguments as an array.
– Example:
function sum(…args) {
return args.reduce((a, b) => a + b);
} - Explain the difference between map() and forEach().
– Answer: map() creates a new array populated with the results of calling a function on every element, whereas forEach() executes a function on each element but does not return a new array. - What is the purpose of Array.prototype.reduce()?
– Answer: The reduce() method executes a reducer function on each element of the array, resulting in a single output value.
– Example:const sum = [1, 2, 3].reduce((acc, curr) => acc + curr, 0); // 6 - How do you clone an object in JavaScript?
– Answer: Using Object.assign(), the spread operator, or JSON.parse(JSON.stringify(object)) for deep cloning.
– Example:
let objClone = { …originalObject }; - What is prototypal inheritance in JavaScript?
– Answer: In JavaScript, objects inherit properties and methods from their prototype. - What is the difference between deep and shallow copy?
– Answer: A shallow copy copies the reference pointers, so nested objects are not copied. A deep copy duplicates everything, including nested objects. - How do you check if a value is an array in JavaScript?
– Answer: Using Array.isArray(value).
– Example: Array.isArray([1, 2, 3]); // true - What is a generator function in JavaScript?
– Answer:– Answer A generator function is a function that can stop midway and then continue from where it stopped.
– Example:
function* generator() {
yield 1;
yield 2;
yield 3;
} - What is the difference between == and === in JavaScript?
– Answer: == checks for value equality with type coercion, whereas === checks for both value and type equality.
Advanced JavaScript Questions
- What is use strict in JavaScript?
– Answer: use strict is a directive that enables strict mode, which helps catch common coding mistakes and “unsafe” actions.
– Example:
‘use strict’;
x = 3.14; // Error: x is not defined - What is a memoization in JavaScript?
– Answer:– Answer Memoization is an optimization technique where you cache the results of expensive function calls and return the cached result when the same inputs occur again. - What is the difference between localStorage and sessionStorage?
– Answer: localStorage persists data even after the browser is closed, whereas sessionStorage only persists data for the duration of the page session. - What is CORS, and how does it work?
– Answer: CORS (Cross-Origin Resource Sharing) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the resource originated. - What is a service worker in JavaScript?
– Answer: A service worker is a script that the browser runs in the background, separate from a web page, enabling features that don’t need a web page or user interaction, such as push notifications and background sync. - What are Promises in JavaScript?
– Answer: Promises represent the eventual completion (or failure) of an asynchronous operation and its resulting value.
– Example:
let promise = new Promise((resolve, reject) => {
// async code
if (success) resolve(result);
else reject(error);
}); - What is the difference between async and defer in a script tag?
– Answer: async downloads the script while the page continues to process, and executes as soon as it’s ready. defer downloads the script during page processing and executes it after the page has finished parsing. - How do you remove duplicates from an array in JavaScript?
– Answer: Using Set or filter().
– Example:
let uniqueArray = […new Set(array)]; - Explain the concept of garbage collection in JavaScript.
– Answer: Garbage collection is the process by which JavaScript automatically frees up memory that is no longer in use or reference. - What are the different ways to create an object in JavaScript?
– Answer: Object literals, constructor functions, ES6 classes, Object.create(), and Object.assign(). - What is the difference between function declaration and function expression?
– Answer: A function declaration defines a named function and is hoisted, whereas a function expression defines an anonymous function and is not hoisted. - What is a promise chain in JavaScript?
– Answer: A promise chain is a sequence of .then() calls, where each call is executed after the previous promise in the chain resolves. - How do you handle exceptions in JavaScript?
– Answer: Using try, catch, finally, and throw statements.
– Example:
try {
// code that may throw an error
} catch (error) {
// handle the error
} finally {
// always executes
} - What is the Temporal Dead Zone (TDZ) in JavaScript?
– Answer: The Temporal Dead Zone is the period between entering the scope where a variable is declared (with let or const) and when it is initialized. - What are symbols in JavaScript?
– Answer:Symbols are unique and immutable primitive values that can be used as keys in objects. - Explain the concept of currying in JavaScript.
– Answer:Currying is a technique of transforming a function with multiple arguments into a sequence of functions, each taking a single argument.
– Example:
function curry(a) {
return function(b) {
return function(c) {
return a + b + c;
};
};
} - What are template literals in JavaScript?
– Answer: Template literals allow embedded expressions and multi-line strings using backticks ( ).
– Example:
let greeting = Hello, ${name}!; - What is the difference between a function constructor and a class in JavaScript?
– Answer: A function constructor is an older way to create objects and instances, while ES6 classes are syntactic sugar over the constructor function pattern. - What is the difference between Object.freeze() and Object.seal()?
– Answer: Object.freeze() makes an object immutable, preventing changes to properties and values. Object.seal() prevents the addition or removal of properties but allows modification of existing ones. - Explain the difference between setTimeout and setInterval.
– Answer: setTimeout executes a function after a specified delay, while setInterval repeatedly executes a function with a fixed time delay between each call.
JavaScript in the Browser
- What is the DOM in JavaScript?
– Answer: The Document Object Model (DOM) is a programming interface that allows scripts to update the content, structure, and style of a document. - How do you select an element by ID in JavaScript?
– Answer: Using document.getElementById(id).
– Example: document.getElementById(“header”); - What is the difference between document.querySelector and document.querySelectorAll?
– Answer: document.querySelector returns the first element that matches a specified CSS selector. document.querySelectorAll returns all elements that match the selector. - How do you add an event listener to an element in JavaScript?
– Answer:Using element.addEventListener(event, function).
– Example:
button.addEventListener(‘click’, () => {
console.log(‘Button clicked!’);
}); - What are preventDefault and stopPropagation in event handling?
– Answer: preventDefault stops the default action of an event, while stopPropagation prevents the event from bubbling up the DOM tree. - What is the difference between the window and document objects in JavaScript?
– Answer: The window object represents the browser’s window, while the document object represents the loaded HTML document. - How do you manipulate classes in the DOM?
– Answer: Using element.classList methods like add, remove, toggle, and contains.
– Example:
element.classList.add(‘active’); - What is event delegation, and why is it useful?
– Answer: Event delegation allows you to add a single event listener to a parent element to manage events for all its children, improving performance and code simplicity. - What is innerHTML and how is it different from textContent?
– Answer: innerHTML returns the HTML content of an element, while textContent returns the text content without any HTML tags. - What is the difference between synchronous and asynchronous JavaScript?
– Answer: Synchronous JavaScript runs in sequence, blocking the next operations until the current one finishes. Asynchronous JavaScript allows multiple tasks to run simultaneously without waiting for each other. - How do you create and dispatch a custom event in JavaScript?
– Answer: Using new CustomEvent() and dispatchEvent().
– Example:
let event = new CustomEvent(‘myEvent’, { detail: { someData: 123 } });
document.dispatchEvent(event); - What is the purpose of the DOMContentLoaded event?
– Answer: The DOMContentLoaded event fires when the HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. - What is the difference between window.onload and DOMContentLoaded?
– Answer: window.onload waits for the entire page to load, including external resources, while DOMContentLoaded fires as soon as the DOM is fully loaded. - How do you store data in the browser using JavaScript?
– Answer: Using Web Storage API (localStorage and sessionStorage), cookies, or IndexedDB. - What is the fetch API, and how is it used?
– Answer:The fetch API is used to make network requests similar to XMLHttpRequest. It returns a promise that resolves to the response of the request.
– Example:
fetch(‘https://api.example.com/data’)
.then(response => response.json())
.then(data => console.log(data));
JavaScript in Practice
- How do you handle asynchronous code in JavaScript?
– Answer:Using callbacks, promises, async/await, and event loops. - What is the purpose of the try-catch block?
– Answer:The try-catch block is used to handle exceptions and errors in a controlled way, preventing them from crashing the program. - What is a JavaScript framework, and can you name a few?
– Answer:A JavaScript framework is a collection of JavaScript libraries and tools that provide a structured way to build web applications. Examples include Angular, React, and Vue.js. - What are polyfills in JavaScript?
– Answer:Polyfills are scripts that provide modern functionality on older browsers
that do not natively support it.
- What is the difference between classical inheritance and prototypal inheritance in JavaScript?
– Answer:Classical inheritance involves classes and objects, while prototypal inheritance involves objects inheriting from other objects without classes. - How do you detect browser features in JavaScript?
– Answer:– Using feature detection libraries like Modernizr or manual checks with if statements.
– Example:
if (‘geolocation’ in navigator) {
// Geolocation available
} - How do you optimize performance in JavaScript?
– Answer: Techniques include minimizing DOM access, using efficient algorithms, avoiding memory leaks, and reducing the complexity of loops and functions. - What is the purpose of setTimeout in JavaScript?
– Answer:setTimeout is used to execute a function after a specified delay.
– Example:
setTimeout(() => {
console.log(‘Hello after 3 seconds’);
}, 3000); - What are the different types of errors in JavaScript?
– Answer: SyntaxError, ReferenceError, TypeError, RangeError, EvalError, and URIError. - How do you debug JavaScript code?
– Answer: Using the browser’s developer tools, console.log() statements, breakpoints, and debuggers. - What is a callback hell in JavaScript?
– Answer: Callback hell refers to the situation where multiple nested callbacks make the code difficult to read and maintain. - How do you prevent callback hell in JavaScript?
– Answer: Using promises, async/await, or by modularizing functions. - What is the new keyword in JavaScript?
– Answer: The new keyword is used to create an instance of a user-defined object type or of one of the built-in object types that has a constructor function. - How do you make an HTTP request in JavaScript?
– Answer: Using XMLHttpRequest, fetch(), or AJAX libraries like Axios.
– Example with fetch():
fetch(‘https://api.example.com/data’)
.then(response => response.json())
.then(data => console.log(data)); - What is the purpose of setInterval in JavaScript?
– Answer: setInterval repeatedly calls a function with a fixed time delay between each call.
– Example:
setInterval(() => {
console.log(‘This will run every 2 seconds’);
}, 2000); - How do you detect a mobile browser in JavaScript?
– Answer: Using the navigator.userAgent property or libraries like MobileDetect.js.
– Example:
const isMobile = /Mobi|Android/i.test(navigator.userAgent); - How do you compare two objects in JavaScript?
– Answer: By comparing their properties manually or using libraries like Lodash.
– Example:
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b); - What are singleton patterns in JavaScript?
– Answer: Singleton patterns restrict the instantiation of a class to a single object. It ensures that a class has only one instance and provides a global point of access to it. - What is the difference between call, apply, and bind in JavaScript?
– Answer: call() and apply() invoke a function immediately with a specific this context. call() accepts arguments individually, while apply() accepts them as an array. bind() returns a new function, permanently binding this to the provided value. - What are factory functions in JavaScript?
– Answer: A factory function is any function that is not a class or constructor that returns an object. - How do you handle errors in asynchronous code?
– Answer: Using .catch() with promises or try-catch with async/await. - What is the difference between querySelector and getElementById?
– Answer: getElementById is faster and only selects elements by their ID, while querySelector can select elements using any CSS selector. - What are transpilers in JavaScript?
– Answer: Transpilers are tools that compile modern JavaScript code into a version that is compatible with older browsers. - How do you add a delay in JavaScript?
– Answer: Using setTimeout or a promise-based delay function.
– Example:
const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); - What are WebSockets in JavaScript?
– Answer: WebSockets provide a way to open a persistent connection between the client and server, allowing for real-time data transfer.
This list covers a broad spectrum of questions that can appear in a JavaScript interview, ranging from basic syntax and concepts to more advanced topics and practical applications. Preparing answers for these will give you a solid foundation to handle most JavaScript-related interview challenges.
Excellent read, I just passed this onto a colleague who was doing a little research on that. And he just bought me lunch since I found it for him smile Thus let me rephrase that: Thank you for lunch! “Love is made in heaven and consummated on earth.” by John Lyly.