JavaScript interview questions
Prepare for your JavaScript interview with these common questions and answers.
01What is the difference between `let`, `const`, and `var`?
var: Function-scoped or globally-scoped. Can be re-declared and updated. Hoisted to the top of its scope.let: Block-scoped ({}). Can be updated but not re-declared in the same scope. Hoisted but not initialized (Temporal Dead Zone).const: Block-scoped. Cannot be updated or re-declared. Must be initialized at declaration. Hoisted but not initialized.
02What is a closure in JavaScript?
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function, even after the outer function has finished executing.
03What is the difference between `null` and `undefined`?
undefined means a variable has been declared but has not yet been assigned a value. It's the default value of uninitialized variables.
null is an assignment value. It can be assigned to a variable as a representation of no value. It is an intentional absence of any object value.
04What is the `this` keyword?
The this keyword refers to the object it belongs to. Its value depends on how a function is called.
- In a method,
thisrefers to the owner object. - Alone,
thisrefers to the global object (windowin browsers). - In a function,
thisrefers to the global object (in strict mode, it'sundefined). - In an event,
thisrefers to the element that received the event. - With arrow functions,
thisis lexically scoped; it refers to thethisof the enclosing scope.
05What is the difference between `==` and `===`?
== (Loose Equality): Compares two values for equality after converting both values to a common type (type coercion).
=== (Strict Equality): Compares two values for equality without performing any type conversion. It checks for both value and type equality.
06What is hoisting?
Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope (the top of the current script or the current function). var declarations are hoisted and initialized with undefined. let and const declarations are hoisted but not initialized, leading to a Temporal Dead Zone.
07What are arrow functions?
Arrow functions are a more concise syntax for writing function expressions. They have two main benefits:
1. Shorter syntax: (a, b) => a + b.
2. Lexical this: They do not have their own this context. Instead, this is determined by the surrounding scope.
08What is a Promise?
A Promise is an object representing the eventual completion or failure of an asynchronous operation. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. A Promise can be in one of three states: pending, fulfilled, or rejected.
09What is `async/await`?
async/await is a modern feature in JavaScript that allows you to work with promises in a more comfortable, synchronous-looking way. An async function always returns a promise. The await keyword can only be used inside an async function and it pauses the execution of the function until the promise is resolved.
10What is the event loop?
The event loop is a mechanism that allows JavaScript, which is single-threaded, to perform non-blocking asynchronous operations. It continuously checks the message queue for new messages (like events or callbacks) and executes them when the call stack is empty.
11What is prototypal inheritance?
Prototypal inheritance is a feature in JavaScript where objects can inherit properties and methods from other objects. Every object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on, until an object is reached with null as its prototype. This is known as the prototype chain.
12What is the difference between `map`, `filter`, and `reduce`?
These are array methods:
map(): Creates a new array by performing a function on each element of the original array.filter(): Creates a new array with all elements that pass the test implemented by the provided function.reduce(): Executes a reducer function on each element of the array, resulting in a single output value.
13What is the DOM?
The DOM (Document Object Model) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as a tree of nodes and objects.
14What is event delegation?
Event delegation is a technique involving adding a single event listener to a parent element that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future. It's more efficient than adding an event listener to every single child element.
15What is the difference between `localStorage` and `sessionStorage`?
localStorage and sessionStorage are both part of the Web Storage API.
localStorage: Stores data with no expiration date. The data will not be deleted when the browser is closed.sessionStorage: Stores data for one session only. The data is deleted when the browser tab is closed.
16What are higher-order functions?
A higher-order function is a function that either takes one or more functions as arguments, or returns a function as its result. map, filter, and reduce are examples of higher-order functions.
17What is the spread operator (`...`)?
The spread syntax (...) allows an iterable such as an array or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. It's also used to make shallow copies of objects and arrays.
18What is the rest parameter (`...`)?
The rest parameter syntax allows a function to accept an indefinite number of arguments as an array. It must be the last parameter in a function definition.
19What is destructuring?
Destructuring assignment is a syntax that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. It provides a more concise way to extract data.
20What is strict mode?
Strict mode ('use strict';) is a way to opt into a restricted variant of JavaScript. It helps you write cleaner code, by catching common coding bloopers and throwing errors. For example, it prevents the use of undeclared variables.
21What is a callback function?
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 routine or action. They are a fundamental part of asynchronous programming in JavaScript.
22What is 'callback hell'?
Callback hell (also known as the pyramid of doom) refers to the situation where callbacks are nested within other callbacks several levels deep, making the code hard to read and maintain. This can be avoided by using Promises or async/await.
23What is the `bind` method?
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. It's used to explicitly set the this context of a function.
24What is the difference between `call`, `apply`, and `bind`?
call(): Invokes a function with a giventhisvalue and arguments provided individually.apply(): Invokes a function with a giventhisvalue and arguments provided as an array.bind(): Returns a new function with a giventhisvalue, without invoking it immediately.
25What is a pure function?
A pure function is a function that meets two criteria:
1. It always returns the same output for the same set of inputs.
2. It has no side effects (it doesn't modify any state outside its scope).
26What is memoization?
Memoization is an optimization technique used to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.
27What is the `typeof` operator?
The typeof operator returns a string indicating the type of the unevaluated operand. For example, typeof 42 returns 'number'. One quirk is that typeof null returns 'object'.
28What is an IIFE (Immediately Invoked Function Expression)?
An IIFE is a JavaScript function that runs as soon as it is defined. It's a design pattern which is also known as a Self-Executing Anonymous Function and contains two major parts: the anonymous function with lexical scope enclosed within the Grouping Operator (), and the immediately invoked function expression () through which the JavaScript engine will directly interpret the function.
29What are template literals?
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They are enclosed by backticks (` ``) instead of single or double quotes.
30What is CORS (Cross-Origin Resource Sharing)?
CORS is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.
Preparing for a role?
Tell us what you’re aiming for. A mentor can help you close the gaps before the interview.