JavaScript is one of the most widely used programming languages for web development. It is used to add dynamic behavior to websites, handle user interactions, communicate with servers, and build modern web applications.
If you are preparing for a JavaScript interview, understanding the fundamentals is important. The following questions cover commonly discussed JavaScript concepts, including variables, functions, promises, closures, events, browser storage, and modules.
1. What is JavaScript?
JavaScript is a high-level, dynamically typed programming language commonly used to create interactive and dynamic web applications.
It can run in web browsers as well as on platforms such as Node.js. In a browser, JavaScript can interact with HTML elements, respond to user actions, make network requests, and update page content without requiring a complete page reload.
2. What are the different types of variables in JavaScript?
JavaScript provides three keywords for declaring variables: var, let, and const.
The var keyword is function-scoped rather than block-scoped. A variable declared with var can be redeclared within the same scope, and its value can also be reassigned.
The let keyword is block-scoped. A variable declared with let can be reassigned, but it cannot be redeclared in the same scope.
The const keyword is also block-scoped. A const variable cannot be reassigned or redeclared in the same scope. However, if a const variable refers to an object or array, the contents of that object or array can still be modified.
Example:
let age = 25;
age = 26;
const user = {
name: "John"
};
user.name = "David";In modern JavaScript, let and const are generally preferred over var.
3. What is hoisting in JavaScript?
Hoisting describes JavaScript's behavior in which certain declarations are processed before the code is executed.
For example, var declarations are hoisted within their scope. However, only the declaration is hoisted, not the assigned value.
Example:
console.log(value); // undefined
var value = 10;Function declarations are also available before their position in the source code.
Example:
sayHello();
function sayHello() {
console.log("Hello");
}It is important to understand that let and const behave differently. They are subject to the temporal dead zone, so accessing them before their declaration results in a ReferenceError.
4. What is the difference between == and === in JavaScript?
The == operator performs a loose equality comparison. It may convert the operands to compatible types before comparing them.
The === operator performs a strict equality comparison. It compares both the value and the data type without performing the usual type coercion associated with ==.
Example:
console.log(5 == "5"); // true
console.log(5 === "5"); // falseIn most situations, === is preferred because it makes comparisons more predictable.
5. What is the difference between undefined and null?
undefined generally indicates that a variable has been declared but does not currently have a value assigned to it.
Example:
let name;
console.log(name); // undefinednull is an intentional value that represents the absence of an object or value.
Example:
let selectedUser = null;Here, null has been explicitly assigned to indicate that there is currently no selected user.
Although both represent an absence of a meaningful value, they have different meanings in JavaScript.
6. What is the difference between synchronous and asynchronous code?
Synchronous code is executed in sequence. Each operation generally needs to finish before the next operation can proceed.
Asynchronous code allows an operation to be started without forcing the entire program to wait for it to finish. This is particularly useful for tasks such as network requests, timers, and other operations that may take some time to complete.
For example, when fetch() is used to request data from a server, JavaScript can continue executing other work while waiting for the response.
7. What are template literals in JavaScript?
Template literals are a convenient way to create strings using backticks (`).
They allow variables and expressions to be inserted directly into a string using ${} syntax. They can also contain multiple lines.
Example:
const name = "John";
const message = `Welcome, ${name}!`;Expressions can also be used inside a template literal.
Example:
const price = 100;
const quantity = 3;
const total = `Total amount: ${price * quantity}`;Template literals make dynamic strings easier to read and maintain.
8. What is an arrow function?
An arrow function is a shorter way of writing a function expression.
Traditional function:
function multiply(a, b) {
return a * b;
}Arrow function:
const multiply = (a, b) => a * b;Arrow functions are especially common when working with array methods such as map(), filter(), and forEach().
One important difference is that arrow functions do not have their own this binding. Instead, they use this from their surrounding lexical scope.
9. What is a rest parameter?
A rest parameter allows a function to accept any number of additional arguments and collect them into an array.
It is written using three dots (...) before the parameter name.
Example:
function sum(...numbers) {
let total = 0;
for (const number of numbers) {
total += number;
}
return total;
}
console.log(sum(10, 20, 30)); // 60A function can have only one rest parameter, and it must be the last parameter in the function definition.
Example:
function example(name, ...values) {
// ...
}Here, name receives the first argument, while values contains the remaining arguments.
10. What is the spread operator?
The spread syntax (...) allows the elements of an iterable, such as an array, to be expanded into individual elements.
Example:
const oddNumbers = [1, 3, 5];
const numbers = [2, 4, 6, ...oddNumbers];
console.log(numbers);
// [2, 4, 6, 1, 3, 5]The spread syntax is commonly used when combining arrays, copying arrays, passing arguments to functions, and creating objects with selected properties.
11. What is array destructuring?
Array destructuring provides a convenient way to extract values from an array and assign them to variables.
Example:
const values = ["Hello", "World"];
const [first, second] = values;
console.log(first); // Hello
console.log(second); // WorldInstead of accessing each array element separately, destructuring allows multiple values to be assigned in a single statement.
12. What is a callback function?
A callback is a function that is passed to another function as an argument so that it can be called later.
Example:
function test(callback) {
callback();
}
test(function () {
console.log("Callback executed");
});Callbacks are commonly used with event handlers, timers, array methods, and asynchronous operations.
Promises and async/await are also widely used for handling asynchronous operations, particularly when multiple asynchronous tasks need to be coordinated.
13. What is a Promise in JavaScript?
A Promise is an object that represents the eventual result of an asynchronous operation.
A Promise can be in one of three states:
Pending — the operation is still in progress.
Fulfilled — the operation completed successfully.
Rejected — the operation failed.
For example:
const promise = fetch("https://example.com/data");
promise
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});Promises make asynchronous code easier to organize and allow multiple operations to be chained together.
14. What are async and await?
async and await provide a cleaner way to work with Promise-based asynchronous operations.
The async keyword is used to declare an asynchronous function. An async function always returns a Promise.
The await keyword can be used inside an async function to wait for a Promise to settle before continuing that particular function.
Example:
async function getData() {
const response = await fetch("https://example.com/data");
const data = await response.json();
return data;
}
getData()
.then(data => {
console.log(data);
});await does not stop the entire JavaScript program. It pauses the execution of the particular async function until the awaited Promise settles.
15. What is AJAX?
AJAX stands for Asynchronous JavaScript and XML.
It is a general approach for communicating with a server asynchronously and updating part of a web page without requiring a complete page reload.
Despite the name, AJAX does not require XML. Modern applications commonly exchange JSON data instead.
Today, developers often use APIs such as fetch() for this type of communication.
16. What is the fetch() method?
fetch() is a Web API used to make network requests.
It returns a Promise that resolves to a Response object.
A common example is:
fetch("https://example.com/data")
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});The second argument can be used to provide request options such as the HTTP method, headers, and request body.
For example:
fetch("https://example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "John"
})
});One important point is that response.json() is a method of the Response object returned by fetch(). It is not a method directly available on the Promise returned by fetch().
17. What is Symbol in JavaScript?
Symbol is a primitive data type in JavaScript.
Every Symbol value is unique, which makes Symbols useful when creating unique object property keys.
Example:
const id = Symbol("id");
const user = {
name: "John",
[id]: 123
};
console.log(user[id]);Symbols can help avoid property-name collisions because each Symbol is unique.
However, Symbols should not be considered a general-purpose mechanism for making object properties truly private.
18. What is a generator function?
A generator is a special type of function that can pause its execution and continue later.
Generator functions are declared using function* and use the yield keyword to produce values.
Example:
function* numbers() {
yield 2;
yield 4;
yield 6;
}
const iterator = numbers();
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());The calls to next() return objects containing value and done properties.
For example:
{ value: 2, done: false }Generators are useful when you want to create custom iterators or produce values one at a time instead of generating all values at once.
19. What is an IIFE?
IIFE stands for Immediately Invoked Function Expression.
It is a function expression that is executed immediately after it is created.
Example:
(function () {
console.log("Function executed");
})();An IIFE can create its own scope, which historically made it useful for preventing temporary variables from becoming global variables.
Although JavaScript modules provide better mechanisms for managing scope in modern applications, IIFEs are still useful in some situations.
20. What is a closure?
A closure occurs when a function retains access to variables from its surrounding lexical scope, even after the outer function has finished executing.
Example:
function createCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3The returned function continues to access the count variable created inside createCounter().
Closures are commonly used for maintaining private state, callbacks, event handlers, and functional programming patterns.
21. What is currying?
Currying is a technique in which a function that normally accepts multiple arguments is transformed into a sequence of functions, with each function receiving one argument.
Example:
function add(a) {
return function (b) {
return a + b;
};
}
const result = add(2)(4);
console.log(result); // 6Here, add(2) returns another function, and passing 4 to that function produces the final result.
Currying can be useful when creating reusable functions or working with functional programming techniques.
22. What is event capturing?
Event capturing is one of the phases of DOM event propagation.
When an event occurs on a nested element, the event can travel from the outermost element down through its ancestors toward the target element.
For example, if a button is inside a div, the event can travel from the document through the div before reaching the button.
Event capturing can be enabled using the capture option:
element.addEventListener("click", handler, {
capture: true
});23. What is event bubbling?
Event bubbling is another phase of event propagation.
In the bubbling phase, an event starts at the target element and then travels upward through its parent elements.
For example, if a button inside a div is clicked, the button can receive the event first, followed by its parent div and then other ancestors.
Example:
container.addEventListener("click", function () {
console.log("Container clicked");
});Event bubbling is commonly used for event delegation.
24. What is the difference between setTimeout() and setInterval()?
setTimeout() schedules a function to run once after a specified delay.
Example:
setTimeout(() => {
console.log("Executed once");
}, 2000);setInterval() schedules a function to run repeatedly at approximately the specified interval.
Example:
setInterval(() => {
console.log("Executed repeatedly");
}, 2000);If an interval is no longer required, it can be stopped using clearInterval().
Similarly, a scheduled timeout can be cancelled using clearTimeout().
25. What is the purpose of "use strict"?
"use strict" enables strict mode for a script or function.
Strict mode changes certain JavaScript behaviors and helps identify some common programming mistakes by turning them into errors.
Example:
"use strict";
myVariable = 10;In strict mode, assigning a value to an undeclared variable causes an error instead of silently creating a global variable.
Modern JavaScript modules and class bodies are already strict mode code, so an explicit "use strict" directive is generally unnecessary there.
26. What are localStorage and sessionStorage?
localStorage and sessionStorage are browser storage mechanisms that allow web applications to store data as key-value pairs.
localStorage keeps data until it is explicitly removed or otherwise cleared by the browser or user.
sessionStorage is associated with a particular browsing session and is generally cleared when that session ends, subject to the browser's storage behavior.
Example:
localStorage.setItem("username", "John");
const username = localStorage.getItem("username");
sessionStorage.setItem("theme", "dark");These storage mechanisms are useful for relatively small amounts of client-side data, such as preferences or temporary application state.
27. What is type coercion in JavaScript?
Type coercion is the conversion of a value from one data type to another.
JavaScript can perform implicit type conversion in certain operations.
Example:
console.log("5" + 2); // "52"Here, the number 2 is converted to a string because the + operator is being used for string concatenation.
Explicit conversion can also be performed.
Example:
const value = "100";
const number = Number(value);
console.log(number); // 100Understanding type coercion is important because unexpected conversions can sometimes lead to confusing results.
28. What is NaN in JavaScript?
NaN stands for Not-a-Number.
Despite its name, NaN is actually a special numeric value in JavaScript. It generally appears when a numeric operation cannot produce a meaningful numeric result.
Example:
const result = Number("hello");
console.log(result); // NaNAnother important characteristic is that NaN is not equal to itself.
console.log(NaN === NaN); // falseTo specifically check whether a value is NaN, Number.isNaN() is usually a good choice.
Example:
console.log(Number.isNaN(NaN)); // true29. What is the arguments object?
The arguments object is an array-like object available inside traditional functions. It contains the arguments passed to that function.
Example:
function showArguments() {
console.log(arguments);
}
showArguments("John", 25, "Developer");The arguments object has a length property and allows individual arguments to be accessed by index.
However, it is not a normal Array.
In modern JavaScript, rest parameters are often preferred when you need to collect function arguments into an actual array.
Example:
function showArguments(...args) {
console.log(args);
}30. What are import and export in JavaScript?
The import and export keywords are used with JavaScript modules.
The export keyword allows functions, variables, classes, or other values to be made available to another module.
Example:
export function add(a, b) {
return a + b;
}Another file can import the function:
import { add } from "./math.js";
console.log(add(2, 3));Modules make it easier to organize large applications by separating code into smaller and reusable files.
31. What are the different ways to loop through an array in JavaScript?
JavaScript provides several ways to iterate over an array.
A traditional for loop can be used when you need precise control over the index.
Example:
const numbers = [10, 20, 30];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}The for...of loop is useful when you simply want to access each array value.
Example:
for (const number of numbers) {
console.log(number);
}The forEach() method can be used when you want to execute a function for every element.
Example:
numbers.forEach(number => {
console.log(number);
});The map() method is useful when you want to create a new array by transforming each element.
Example:
const doubled = numbers.map(number => number * 2);The filter() method can be used when you want to create a new array containing only elements that satisfy a condition.
Example:
const result = numbers.filter(number => number > 15);The for...in loop can technically be used with arrays, but it iterates over enumerable property keys rather than array values. Therefore, it is generally better suited to objects than normal array iteration.
Conclusion
These JavaScript interview questions cover many of the concepts commonly encountered when learning JavaScript or preparing for technical interviews. Knowing the definition of a concept is useful, but understanding how and when to use it is even more important.
When preparing for an interview, try to understand the behavior behind each concept and practice writing small examples. Concepts such as closures, Promises, async/await, event propagation, destructuring, rest and spread syntax, and JavaScript modules become much easier to understand once you have used them in real code.
JavaScript continues to evolve, so it is also worth keeping your knowledge aligned with modern language features and current browser APIs.