JavaScript Interview Questions for Freshers
JavaScript Interview Questions for Freshers
1
Functions, Closures, and Callbacks
• What is a function declaration vs. a function expression? A function declaration uses the
function keyword at the top level (e.g. function foo() {} ), while a function expression
assigns a function to a variable (e.g. const foo = function() {} ). Declarations are hoisted
(you can call foo() before its declaration in code), whereas expressions are not (the variable
must exist first) 9 .
• What are arrow functions? Arrow functions ( => ) provide a shorter syntax for writing
functions. For example, const add = (a, b) => a + b; . They also inherit this lexically
from the enclosing scope 10 . Arrow functions cannot be used as constructors and do not have
their own arguments object.
• What is a callback function? A callback is a function passed as an argument to another
function, which is then invoked inside the outer function. Callbacks are widely used for
asynchronous operations or event handling. For example:
Here, sayGoodbye is a callback that runs after greet logs its message 11 .
• What are closures? A closure occurs when an inner function retains access to variables from its
outer (enclosing) function scope, even after the outer function has finished executing 12 . In
other words, the inner function “closes over” the outer scope. For example:
function outer() {
let x = 10;
return function inner() {
console.log(x);
}
}
const fn = outer();
fn(); // logs 10
Here, inner still accesses x even after outer has returned 12 . Closures are useful for data
privacy and callbacks.
• What is strict mode ( "use strict" )? Strict mode is a way to opt in to a restricted variant of
JavaScript. It disallows certain bad syntax (like duplicate parameter names), prevents creation of
implicit globals, and makes errors more visible. You enable it by adding "use strict"; at the
top of your script or function. In strict mode, for example, assigning to an undeclared variable
throws a ReferenceError 13 .
ES6+ Features
• What are rest parameters and the spread operator? The rest parameter syntax ...args in
a function definition collects all remaining arguments into an array (e.g. function
sum(...nums) {} ) 14 . The spread operator ( ... ) does the opposite: it expands an iterable
2
(like an array) into individual elements. For example, Math.max(...[3,5,1]) is equivalent to
Math.max(3,5,1) . It can also spread object properties into a new object 15 .
• What is destructuring assignment? Destructuring lets you unpack values from arrays or
properties from objects into distinct variables. For example, const [a, b] = [1, 2]; sets
a=1 and b=2 . For objects: const {x, y} = {x:10, y:20}; extracts x and y into
variables 16 . This syntax makes it easy to work with data by extracting only needed parts.
• What are Promises? A Promise is an object representing the eventual completion (success) or
failure of an asynchronous operation 17 . It has three possible states: pending (initial), fulfilled
(completed successfully), or rejected (failed). Promises provide .then() and .catch()
methods to handle success or error cases. For example:
• What are async/await keywords? async / await provide syntax for writing asynchronous
code in a synchronous style. Marking a function async means it returns a Promise. Within it,
the await keyword can pause execution until a Promise resolves or rejects. For example,
await fetch(url) waits for the HTTP request to complete. Using try / catch with async/
await simplifies error handling. Under the hood, it’s syntactic sugar over Promises 18 .
• How do you prevent default browser behavior for an event? Inside an event handler, call
event.preventDefault() to stop the browser’s default action. For example,
link.addEventListener("click", e => { e.preventDefault(); /* handle click
without navigating */ }); 23 .
• What is localStorage vs. sessionStorage ? Both are web Storage APIs for persisting key-
value data in the browser. The difference is lifetime: localStorage data persists indefinitely
(even after closing the browser) and is shared across tabs of the same origin, whereas
sessionStorage data is limited to a single tab session and is cleared when that tab is closed
24 . Both store only strings (you can JSON-encode objects).
3
Objects and Arrays
• How do you create objects and arrays? An object can be created using an object literal: e.g.
const obj = {name: "John", age: 17}; . You can also use constructors or
Object.create() . An array is created with brackets: e.g. let arr = [1, 2, 3] or new
Array(5) .
• What is the difference between an array and an object? Arrays are specialized objects used
for ordered collections indexed by numbers; they come with array methods and a numeric
length . Objects are unordered collections of key-value pairs indexed by string keys. In
practice, arrays should be used when data is list-like, and plain objects for records or maps 25 .
• How do you iterate over arrays? You can use loops ( for , for...of ), or array methods like
.forEach() , .map() , .filter() . For example, arr.forEach(x =>
console.log(x)); or const doubled = arr.map(x => x*2) .
• How can you remove duplicates from an array? One simple way is to use a Set : e.g.
[...new Set(arr)] creates a new array of unique values. Alternatively, you can filter with
index checking. For example:
4
schedule tasks. Note that callbacks run via the event loop and do not block other code. (Similarly,
setInterval() repeats execution at intervals.) For example:
js
console.log("Start");
setTimeout(() => { console.log("Delayed"); }, 2000);
console.log("End");
// Output: Start, End, (2s pause), Delayed 33 .
• What is the event loop? JavaScript uses a single-threaded runtime with an event loop. When
functions are called, their execution contexts go on the call stack. Asynchronous callbacks (from
setTimeout , I/O, promises, etc.) go into a task (callback) queue. The event loop continuously
checks: if the call stack is empty, it takes the next callback from the queue and pushes it onto the
stack 34 . This mechanism allows JS to handle asynchronous operations without blocking, even
though the main thread is single-threaded.
• How do promises and callbacks fit into this? A callback passed to an async API will be queued
when the operation completes (e.g. after a timeout or HTTP response). Promises work similarly
but allow chaining. For example, fetch(url).then(response => ...) will queue the
then handler via the event loop when the HTTP request finishes. Understanding the event loop
helps explain why setTimeout(fn, 0) still defers fn until after the current code.
try {
JSON.parse(badString);
} catch(e) {
console.error("Invalid JSON:", e);
}
Browsers also show uncaught errors in the console with stack traces, which helps locate the
problem.
• What is the debugger statement? Inserting debugger; into code acts like a breakpoint: it
pauses execution at that line when DevTools are open, allowing you to step through code line by
line 7 . This is useful for inspecting state at a precise point.
5
data').then(res => res.json()).then(data => console.log(data)) makes an
asynchronous request without callbacks 36 .
• What is localStorage ? The localStorage API allows storing key-value string data in the
browser persistently. You use localStorage.setItem(key, value) and
localStorage.getItem(key) to store and retrieve data. It has no expiration (unlike cookies)
and is scoped per domain.
• What is sessionStorage ? Similar to localStorage , but it stores data for only one session
(it is cleared when the tab/window is closed) 37 . Use it for data that should not persist beyond
the current browsing session.
Sources: Core concepts here are gathered and summarized from JavaScript interview guides and
documentation 1 2 4 10 38 24 30 12 . These cover data types, operators, scoping, ES6
features, DOM methods, and other frequently asked topics. Each answer above is supported by these
authoritative references.