If you’re preparing for a JavaScript interview, it’s essential to be ready to answer common questions that test your understanding of the language. Whether you’re a beginner or an experienced developer, mastering these questions will help you explain complex concepts clearly, which is often what interviewers are looking for. Here are 20 commonly asked JavaScript interview questions with clear explanations and examples to ensure you are well-prepared.
1. What is JavaScript?
JavaScript is a dynamic, high-level programming language that is widely used for building web applications. It allows you to create interactive elements on web pages, such as forms, dynamic content updates, and more.
Example:
<button onclick="alert('Hello, World!')">Click me</button>
This simple JavaScript code will display an alert box with the message “Hello, World!” when you click the button.
2. What is the difference between var
, let
, and const
?
var
: Function-scoped, can be redeclared, hoisted to the top of the scope.let
: Block-scoped, cannot be redeclared in the same scope, not hoisted likevar
.const
: Block-scoped, cannot be redeclared or reassigned after the initial declaration.
Example:
var name = "John"; // Can be redeclared
let age = 25; // Block-scoped, cannot be redeclared
const pi = 3.14; // Cannot be reassigned
3. What are closures in JavaScript?
A closure is when a function retains access to its parent scope, even after the parent function has closed. This allows the function to “remember” the variables from its outer scope.
Example:
function outer() {
let counter = 0;
return function inner() {
counter++;
console.log(counter);
};
}
const increment = outer();
increment(); // 1
increment(); // 2
Here, inner()
retains access to counter
even after outer()
has finished executing.
4. Explain event delegation.
Event delegation allows you to handle events at a higher level in the DOM, rather than attaching event listeners to specific elements. This is particularly useful when dealing with dynamic elements.
Example:
document.getElementById('parent').addEventListener('click', function(e) {
if (e.target && e.target.nodeName === "BUTTON") {
console.log("Button clicked");
}
});
In this example, instead of adding event listeners to each button, we add one listener to the parent, and the event is delegated to the child elements.
5. What is the difference between ==
and ===
in JavaScript?
==
: Compares values but not types. This is known as loose equality.===
: Compares both values and types. This is strict equality.
Example:
console.log(5 == '5'); // true (loose comparison)
console.log(5 === '5'); // false (strict comparison)
6. What are Promises in JavaScript?
Promises are a way to handle asynchronous operations in JavaScript. They represent an operation that hasn’t completed yet but is expected to in the future.
Example:
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Done!"), 1000);
});
myPromise.then(result => console.log(result)); // Logs "Done!" after 1 second
7. What is the difference between null
and undefined
?
null
: Explicitly set by the programmer to indicate the absence of a value.undefined
: Indicates that a variable has been declared but not assigned a value.
Example:
let a; // `a` is undefined
let b = null; // `b` is explicitly set to null
8. Explain this
in JavaScript.
this
refers to the context in which the function is executed. Its value depends on where the function is called, not where it is defined.
Example:
const person = {
name: 'John',
greet: function() {
console.log(this.name);
}
};
person.greet(); // Outputs 'John'
Here, this
refers to the person
object.
9. What is an IIFE (Immediately Invoked Function Expression)?
An IIFE is a function that runs as soon as it is defined. It helps in creating a local scope, preventing variables from polluting the global scope.
Example:
(function() {
console.log('I am an IIFE!');
})();
10. What is hoisting in JavaScript?
Hoisting is JavaScript’s behavior of moving declarations (not initializations) to the top of their scope before code execution.
Example:
console.log(x); // undefined
var x = 5;
The declaration var x
is hoisted, but the assignment (x = 5
) is not, hence undefined
is logged.
11. What is the call()
, apply()
, and bind()
method?
call()
: Invokes a function with a giventhis
context and arguments provided individually.apply()
: Similar tocall()
, but arguments are provided as an array.bind()
: Returns a new function with a giventhis
context, but doesn’t execute it immediately.
Example:
function greet(greeting) {
console.log(greeting + ', ' + this.name);
}
const person = { name: 'John' };
greet.call(person, 'Hello'); // "Hello, John"
greet.apply(person, ['Hi']); // "Hi, John"
const greetJohn = greet.bind(person);
greetJohn('Hey'); // "Hey, John"
12. Explain async
and await
.
async
and await
are modern ways to handle asynchronous code. async
makes a function return a Promise, and await
pauses the function execution until the Promise is resolved.
Example:
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
}
fetchData();
13. What is map()
, filter()
, and reduce()
in JavaScript?
map()
: Creates a new array by applying a function to each element of the original array.filter()
: Creates a new array with elements that pass a condition.reduce()
: Reduces the array to a single value by applying a function to each element.
Example:
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2); // [2, 4, 6, 8]
const even = numbers.filter(num => num % 2 === 0); // [2, 4]
const sum = numbers.reduce((acc, num) => acc + num, 0); // 10
14. What is event bubbling and event capturing?
Event bubbling is when an event starts from the deepest element and bubbles up to the parent elements. Event capturing is the opposite, where the event is first captured by the outermost element and propagated down to the target element.
15. Explain prototype
in JavaScript.
Every JavaScript object has a prototype
from which it can inherit properties and methods. Functions have a prototype
property, which is used to build new objects.
Example:
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
const john = new Person('John');
john.greet(); // "Hello, my name is John"
16. What is the difference between synchronous and asynchronous code?
- Synchronous: Code is executed line-by-line, and each line waits for the previous one to finish.
- Asynchronous: Code can run in parallel, without waiting for other operations to complete.
Example:
console.log('Start');
setTimeout(() => console.log('Async'), 0);
console.log('End');
Output:
Start
End
Async
17. What is NaN
in JavaScript?
NaN
stands for “Not-a-Number.” It’s a value representing a computational error when performing mathematical operations.
Example:
console.log(0 / 0); // NaN
18. What is typeof
operator?
typeof
is an operator used to determine the data type of a variable.
Example:
console.log(typeof 'Hello'); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
19. What is a callback
function?
A callback
function is a function passed into another function as an argument, which is then executed after some operation is completed.
Example:
function fetchData(callback) {
setTimeout(() => {
console.log('Data fetched');
callback();
}, 1000);
}
fetchData(() => {
console.log('Callback executed');
});
20. What is destructuring in JavaScript?
Destructuring is a way to unpack values from arrays or properties from objects into distinct variables.
Example:
const [a, b] = [1, 2]; // Array destructuring
const { name, age } = { name: 'John', age: 25 }; // Object destructuring
Conclusion
Mastering JavaScript interview questions goes beyond simply knowing definitions. You need to be able to explain concepts clearly and provide examples that demonstrate your depth of understanding. Use these 20 questions as a guide, and make sure to practice your explanations so you’re not just reciting textbook answers, but offering insights with confidence. Additionally, if you want to thoroughly prepare before the interview, I recommend reading Cracking the Coding Interview: 189 Programming Questions and Solutions. It has helped many people excel in their coding interviews. Best of luck with your preparation!