Prepare for Your JavaScript Interview: Basic to Advanced Questions
Master JavaScript interview questions across all experience levels. This comprehensive guide covers 30 essential JavaScript questions arranged from basic concepts for freshers to advanced scenarios for experienced developers. Perfect for 0-6+ years of experience.
Basic JavaScript Questions (Freshers & 0-1 Year Experience)
1. What are the different data types in JavaScript?
JavaScript has two categories of data types: primitive and non-primitive. Primitive types include String, Number, Boolean, Null, Undefined, Symbol, and BigInt. Non-primitive types include Object (which encompasses arrays, functions, and more).[2][4]
2. What is the difference between == and ===?
== performs type coercion before comparison (loose equality), while === compares both value and type without coercion (strict equality).
console.log(5 == '5'); // true (type coercion)
console.log(5 === '5'); // false (different types)
[2]
3. What is the output of 3 + 2 + "7"?
The output is "57". JavaScript evaluates left to right: 3 + 2 becomes 5, then 5 + "7" performs string concatenation resulting in "57"
4. Explain hoisting in JavaScript.
Hoisting moves variable and function declarations to the top of their scope during compilation. Only declarations are hoisted, not initializations.
console.log(x); // undefined (not ReferenceError)
var x = 5;
[4]
5. What are truthy and falsy values in JavaScript?
Falsy values are false, 0, -0, 0n, "", null, undefined, and NaN. All other values are truthy.[4]
6. What is the difference between var, let, and const?
var has function scope and can be redeclared/reassigned. let and const have block scope. let can be reassigned, const cannot.
if(true) {
var x = 10;
let y = 20;
const z = 30;
}
console.log(x); // 10 (function scope)
console.log(y); // ReferenceError (block scope)
[2]
7. What is NaN and how do you check for it?
NaN means "Not a Number" and represents an invalid mathematical operation. Use isNaN(value) or Number.isNaN(value) to check.
console.log(isNaN('hello')); // true
console.log(Number.isNaN('hello')); // false
8. What does typeof null return?
typeof null returns "object". This is a historical bug in JavaScript, but null is actually a primitive value.[6]
9. What is the output of [] + []?
The output is "" (empty string). Both empty arrays convert to empty strings during concatenation.[2]
10. Explain the difference between null and undefined.
undefined means a variable has been declared but not assigned. null is an intentional absence of value assigned by the programmer.[2]
Intermediate JavaScript Questions (1-3 Years Experience)
11. What is closure in JavaScript?
A closure is a function that retains access to variables from its outer (enclosing) scope even after the outer function has returned.
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2
12. What is event bubbling and how to stop it?
Event bubbling is when an event triggers on child elements first, then propagates to parent elements. Use event.stopPropagation() to stop it.
document.querySelector('div').addEventListener('click', function(e) {
console.log('Div clicked');
e.stopPropagation();
});
13. Explain this keyword in different contexts.
In global scope, this is window. In object methods, this refers to the object. In arrow functions, this inherits from the parent scope.[2]
14. What are arrow functions and their limitations?
Arrow functions provide concise syntax and lexically bind this. They cannot be used as constructors and lack their own this, arguments, or super.
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
15. What is destructuring in JavaScript?
Destructuring allows extracting values from arrays/objects into distinct variables.
const person = { name: 'John', age: 30 };
const { name, age } = person;
console.log(name, age); // John 30
const arr = [1, 2, 3];
const [first, second] = arr;
console.log(first, second); // 1 2
Advanced JavaScript Questions (3-6+ Years Experience)
16. Explain the event loop in JavaScript.
The event loop handles asynchronous operations. It processes the call stack, then microtask queue (Promises), then macrotask queue (setTimeout, etc.).
17. What is a Promise and how does it work?
A Promise represents an asynchronous operation with three states: pending, fulfilled, or rejected. Use .then(), .catch(), and .finally() to handle results.
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('Success!'), 1000);
});
promise.then(result => console.log(result));
18. What is async/await and how does it improve Promises?
async/await provides cleaner syntax for handling Promises. async functions return Promises, and await pauses execution until the Promise settles.
async function fetchData() {
try {
const data = await fetch('api/data');
return data.json();
} catch (error) {
console.error('Error:', error);
}
}
19. What is debouncing and when would you use it at Paytm?
Debouncing delays function execution until after a wait period has elapsed since the last invocation. Useful for search inputs or scroll events at high-traffic platforms like Paytm.[5]
function debounce(func, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), delay);
};
}
20. Explain prototypal inheritance in JavaScript.
Every object has a prototype. Properties/methods can be inherited through the prototype chain using Object.create() or constructor functions.[5]
21. What is the difference between call, apply, and bind?
All change this context. call and apply invoke immediately (apply takes array arguments). bind returns a new function without invoking.
22. How does Object.freeze() work?
Object.freeze() makes an object immutable by preventing additions, deletions, and value changes. Nested objects need recursive freezing.
const obj = { prop: 1 };
Object.freeze(obj);
obj.prop = 2; // Silent failure
23. What are generators and how do they work?
Generators are functions that pause and resume execution using yield. They return iterator objects for lazy evaluation.
function* numberGen() {
yield 1;
yield 2;
yield 3;
}
const gen = numberGen();
console.log(gen.next().value); // 1
24. Explain strict mode in JavaScript.
Strict mode ('use strict') eliminates silent errors, enforces better coding practices, and prevents undeclared variables.[4]
25. What is throttling and how is it different from debouncing?
Throttling limits function execution to once per time interval regardless of calls. Debouncing waits for a pause. Use throttling for scroll/resize events.[5]
Scenario-Based JavaScript Questions (All Levels)
26. How would you handle API errors at Zoho using async/await?
Use try-catch blocks around await calls and provide user-friendly error messages with retry logic.
async function fetchUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) throw new Error('User not found');
return await response.json();
} catch (error) {
console.error('API Error:', error);
return null;
}
}
27. Create a function at Salesforce to deep clone an object.
Use JSON.parse(JSON.stringify()) for simple cloning or implement recursive cloning for functions/dates.
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
28. How would you optimize a slow search function at Flipkart?
Implement debouncing, use efficient data structures (Maps/Sets), and consider web workers for heavy computations.
29. At Atlassian, how would you manage memory leaks in event listeners?
Always remove event listeners using removeEventListener when components unmount. Store references to avoid garbage collection issues.
30. Design a caching mechanism for API calls at Adobe using JavaScript.
Use a Map to store responses with timestamps. Implement TTL (Time To Live) and size limits for cache eviction.
const cache = new Map();
function getCachedData(key, ttl = 300000) {
const cached = cache.get(key);
if (cached && Date.now() - cached.timestamp < ttl) {
return cached.data;
}
return null;
}