Top javascript interview questions and answers

JavaScript Interview Questions & Answers
1. What is prototype in JavaScript?
A prototype is like a blueprint that objects use to share features. If an object doesn’t have a method or property, JavaScript checks its prototype. This allows objects to reuse code.
let arr = [1, 2, 3];
arr.push(4); // 'push' comes from Array's prototype
2. What are promises and how do they work?
A Promise is a JavaScript object that represents the eventual completion (or failure) of an asynchronous operation. It has three states: pending: initial state fulfilled: operation completed successfully rejected: operation failed
const promise = new Promise((resolve, reject) => {
// async work
if (success) resolve(data);
else reject(error);
});
promise
.then(result => console.log(result))
.catch(error => console.error(error));
3. What is the difference between Promise.all and Promise.allSettled?
Promise.all([...]) Waits for all promises to fulfill. If any promise rejects, the entire result is rejected. Promise.allSettled([...]) Waits for all promises to settle (either fulfilled or rejected). It returns an array of result objects with { status, value/reason }.
4. How does async/await work?
async functions always return a Promise. Inside them, you can use await to pause execution until a Promise resolves or rejects.
async function fetchData() {
try {
const data = await fetch('/api/data');
const json = await data.json();
return json;
} catch (err) {
console.error(err);
}
}
It makes asynchronous code look synchronous and easier to read/manage than chained .then() calls.
5. What is hoisting in JavaScript?
In JavaScript hoisting refers to the built in behavior of the language through which declarations of function variable and classes are moved to the top of their scope all before code execute this allows us to use functions, variables and classes before they are declared. Hoisting is JavaScript’s behavior of moving declarations (not initializations) to the top of their scope during compilation. var is hoisted and initialized as undefined. let and const are hoisted but not initialized (they remain in the "temporal dead zone"). Functions are hoisted completely (declaration + body).
Example:
console.log(x); // undefined
var x = 5;
6. What is the difference between var, let, and const?
var: Function-scoped, can be re-declared and updated. let: Block-scoped, can be updated but not re-declared in the same scope. const: Block-scoped, cannot be re-assigned or re-declared.
7. What are JavaScript data types?
- Primitive: String, Number, Boolean, Null, Undefined, Symbol, BigInt
- Non-Primitive: Object (includes Arrays, Functions, etc.)
8. What is the difference between == and ===?
== (loose equality): compares values after type conversion === (strict equality): compares both value and type '5' == 5 // true '5' === 5 // false
9. What are closures in JavaScript?
A closure is when a function retains access to its lexical scope (the variables of its parent function) even after the parent function has finished executing. In other words, closures allow functions to "remember" and use variables from the environment in which they were created.
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
counter(); // 1
counter(); // 2
10. What is the difference between null and undefined?
undefined: a variable declared but not assigned a value. null: an assigned value representing "no value"
11. What is the event loop in JavaScript?
The event loop allows JavaScript (single-threaded) to handle asynchronous tasks like I/O without blocking the main thread. It checks the call stack and message queue, running queued tasks when the stack is empty.
12. What are arrow functions and how are they different?
Arrow functions are a shorter syntax for writing functions. They do not have their own this, arguments, or super.
const add = (a, b) => a + b;
13. What is a higher-order function?
A function that:
- Takes another function as an argument,
- Or returns another function. Examples: map, filter, reduce]
14. What are template literals?
Strings enclosed with backticks (`), allowing: Embedded expressions: ${} Multi-line strings
const name = "Waleed";
console.log(`Hello, ${name}!`);
15. What are ES6 Features?
Arrow Functions, Template Literals, Destructuring: Extract Properties from objects or arrays.
const {name} = user.
16. JavaScript is single-threaded?
Yes, JavaScript is single-threaded, meaning it has a single call stack and can execute one task at a time. This single-threaded nature is what allows JavaScript to be simple and predictable in execution.
17. what is call stack?
A call stack is a data structure in JavaScript that keeps track of function execution. It follows the Last In, First Out (LIFO) principle, meaning the last function that is called is the first one to finish and be removed from the stack. When a function is invoked, it is pushed onto the stack. Once the function finishes executing, it is popped off the stack, and control returns to the previous function. Execution order (call stack behavior):
- first() is called → pushed onto stack
- second() is called inside first() → pushed on top of first()
- third() is called inside second() → pushed on top of second()
- third() finishes → popped from stack → control goes back to second()
- second() finishes → popped from stack → control goes back to first()
- first() finishes → popped from stack
Isn't it bad that a function waits while other functions above it execute? Doesn't it block things? That’s a great point, and it’s true that synchronous code in the call stack can block the main thread. This is why long-running or slow operations—like network requests or heavy computations—can make the UI unresponsive.
However, JavaScript handles this with asynchronous programming. Using callbacks, Promises, or async/await, these operations are offloaded to the Web APIs or background threads. The call stack remains free to execute other code, and the slow operation’s result is handled later via the event loop. So, while the call stack itself is single-threaded, JavaScript avoids blocking the main thread using async mechanisms, which is why it works efficiently even with long-running tasks.
18. what is event loop?
The event loop is a mechanism in JavaScript that allows it to handle asynchronous operations while still being single-threaded. Since JavaScript executes code on a single thread, long-running tasks (like network requests, timers, or file I/O) could block execution if handled synchronously. The event loop solves this by:
- Keeping track of the call stack (where functions are executed).
- Checking the task queue (where asynchronous callbacks, Promises, and events wait).
- Pushing tasks from the queue to the call stack only when the stack is empty. This ensures that JavaScript can continue executing other code while waiting for async operations, making the language non-blocking and efficient.
19. What is task queue?
The task queue (also called the callback queue) is a queue where asynchronous tasks wait to be executed in JavaScript. These tasks include things like callbacks from setTimeout, DOM events, or network requests. When the call stack is empty, the event loop takes the first task from the task queue and pushes it onto the call stack for execution. This is how JavaScript handles asynchronous operations without blocking the main thread. SetTimeout and SetInterval SetTimeout: Executes a function once after a specified delay. SetInterval: Executes a function repeatedly at a specified interval until cleared.
Comments (0)
No comments yet. Be the first!