15 common JavaScript interview questions
1. What is the difference between '==' and '===' operators
in JavaScript?
Answer:
'==' is the equality operator that compares
values after type conversion, while '===' is the strict equality operator that compares
both value and type without conversion. For example, '5 == "5"'
returns true, but '5 === "5"' returns false.
2. Explain closures in JavaScript.
Answer:
A closure is a function that has access to
variables in its outer (enclosing) function's scope chain, even after the outer
function has returned. Closures retain access to all variables within their
scope at the time of creation. They're commonly used to create private
variables and for factory functions.
3. What is event bubbling in JavaScript?
Answer:
Event bubbling is a mechanism where an
event triggered on a nested element will 'bubble up' through its ancestor
elements in the DOM tree. When an event occurs on an element, it first runs the
handlers on that element, then on its parent, and so on up the chain, unless
explicitly stopped with event.stopPropagation().
4. What is the difference between let, const, and var in
JavaScript?
Answer:
var is function-scoped and can be
redeclared and updated. let is block-scoped and can be updated but not
redeclared within its scope. const is block-scoped and neither can be updated
nor redeclared after initialization. Both let and const are hoisted but not
initialized, resulting in a 'temporal dead zone'.
5. Explain the concept of hoisting in JavaScript.
Answer:
Hoisting is JavaScript's default behavior
of moving declarations to the top of the current scope before code execution.
Function declarations and var variables are hoisted, meaning they can be used
before declaration. However, var variables are initialized with undefined while
function declarations are fully hoisted. let and const are hoisted but not
initialized, triggering a ReferenceError if accessed before declaration.
6. What is a Promise in JavaScript?
Answer:
A Promise is an object representing the
eventual completion or failure of an asynchronous operation and its resulting
value. It allows asynchronous methods to return values like synchronous methods
instead of immediately returning the final value. A Promise can be in one of
three states: pending, fulfilled, or rejected. It provides methods like
.then(), .catch(), and .finally() to handle the results.
7. How does prototypal inheritance work in JavaScript?
Answer:
In JavaScript, objects inherit properties
and methods from their prototype. When a property or method is accessed on an
object, JavaScript first looks for it on the object itself. If not found, it
looks at the object's prototype, and continues up the prototype chain until it
finds it or reaches an object with a null prototype. This mechanism allows
objects to inherit from other objects, forming a prototype chain.
8. What is the event loop in JavaScript?
Answer:
The event loop is JavaScript's mechanism
for handling asynchronous operations. It continuously checks the call stack and
the callback queue. When the call stack is empty, it takes the first event from
the queue and pushes it to the call stack to be executed. This process repeats,
allowing JavaScript to handle non-blocking operations despite being
single-threaded.
9. Explain how 'this' keyword works in JavaScript.
Answer:
The value of 'this' depends on how a
function is called: 1) In global scope, it refers to the global object (window
in browsers). 2) In object methods, it refers to the object the method belongs
to. 3) In a function called with new, it refers to the newly created instance.
4) In arrow functions, it retains the 'this' value of the enclosing lexical
context. 5) Functions called with call(), apply(), or bind() can have their
'this' value explicitly set.
10. What are arrow functions and how do they differ from
regular functions?
Answer:
Arrow functions are a concise syntax
introduced in ES6. They differ from regular functions in several ways: 1) They
don't have their own 'this' binding (it's lexically bound to the surrounding
context). 2) They cannot be used as constructors (no 'new' keyword). 3) They
don't have their own arguments object. 4) They don't have a prototype property.
5) They cannot be used as generators (no yield keyword).
11. Describe the difference between synchronous and
asynchronous code in JavaScript.
Answer:
Synchronous code executes sequentially,
with each operation completing before the next one begins, potentially blocking
the thread. Asynchronous code allows operations to be initiated and then
continue execution without waiting for the operation to complete. The
completion is handled later via callbacks, promises, or async/await syntax,
enabling non-blocking behavior for operations like API calls, timers, or file
operations.
12. What is the purpose of the async/await syntax in
JavaScript?
Answer:
async/await is syntactic sugar built on
promises that makes asynchronous code easier to write and read by allowing it
to be structured like synchronous code. An async function returns a promise
implicitly, and the await keyword pauses execution until the promise resolves,
without blocking the main thread. This eliminates callback chains and makes
error handling more intuitive using traditional try/catch blocks.
13. Explain the concept of currying in JavaScript.
Answer:
Currying is a functional programming
technique where a function with multiple arguments is transformed into a
sequence of functions, each taking a single argument. Instead of calling a
function with all arguments at once, you can call it with a single argument and
get back a function that accepts the next argument, and so on. This enables
partial application, function composition, and creating specialized functions
from more general ones.
14. What are WeakMap and WeakSet in JavaScript?
Answer:
WeakMap and WeakSet are collection objects
that hold weak references to their keys (WeakMap) or values (WeakSet), allowing
those objects to be garbage-collected if there are no other references to them.
Unlike Map and Set, they can't be iterated over, don't have a size property,
and don't prevent garbage collection. WeakMap keys must be objects, and WeakSet
can only contain objects. They're useful for storing metadata about objects
without causing memory leaks.
15. What is the difference between null and undefined in
JavaScript?
Answer:
undefined means a variable has been
declared but not assigned a value, or an object property/array element doesn't
exist. It's the default return value for functions without an explicit return
statement. null is an explicit assignment value representing 'no value' or
'empty'. It's a primitive value that represents the intentional absence of any
object value. typeof undefined returns 'undefined', while typeof null returns
'object' (a historical bug in JavaScript).