Top 50 JavaScript Interview Questions for Entry-Level Developers
Preparing for your first JavaScript interview can feel overwhelming. Hiring managers typically test a mix of fundamentals, problem-solving ability, and practical coding skills. This tutorial walks you through the 50 most commonly asked JavaScript interview questions for entry-level developers, complete with explanations, code examples, and best practices. By the end, you'll have a solid mental map of what to expect and how to answer confidently.
Why These Questions Matter
Interview questions aren't just trivia — they reveal how well you understand JavaScript's core mechanics. Concepts like hoisting, closures, the event loop, and asynchronous behavior separate developers who can build features from those who can debug them. Mastering these questions helps you write cleaner code and reason about edge cases that appear in real-world applications.
JavaScript Fundamentals
1. What is JavaScript?
JavaScript is a high-level, interpreted programming language primarily used for adding interactivity to web pages. It runs in browsers and on servers (via Node.js), supporting event-driven, functional, and object-oriented programming styles.
2. What are the differences between JavaScript and Java?
Despite the similar name, they are entirely different languages. Java is statically typed and compiled; JavaScript is dynamically typed and interpreted. Java uses class-based inheritance, while JavaScript uses prototype-based inheritance.
3. What are JavaScript data types?
JavaScript has eight data types: String, Number, Boolean, Undefined, Null, Symbol, BigInt, and Object. The first seven are primitives; objects are reference types.
4. What is the difference between let, const, and var?
var x = 1; // function-scoped, can be redeclared
let y = 2; // block-scoped, can be reassigned
const z = 3; // block-scoped, cannot be reassigned
var is function-scoped and hoisted with a default value of undefined. let and const are block-scoped and exist in the temporal dead zone until declared. Prefer const by default, let when reassignment is needed, and avoid var.
5. What is hoisting?
Hoisting moves variable and function declarations to the top of their scope during compilation. Function declarations are fully hoisted; var variables are hoisted but initialized as undefined; let and const are hoisted but not initialized.
console.log(a); // undefined
var a = 5;
console.log(b); // ReferenceError
let b = 10;
6. What is the difference between == and ===?
== performs type coercion before comparison, while === checks both value and type. Always prefer === to avoid unexpected behavior.
console.log(0 == false); // true
console.log(0 === false); // false
console.log("1" == 1); // true
console.log("1" === 1); // false
7. What is type coercion?
Type coercion is the automatic conversion of values from one type to another. JavaScript performs implicit coercion in operations like + and ==, which can lead to surprising results.
8. What is the typeof operator?
typeof "hello"; // "string"
typeof 42; // "number"
typeof undefined; // "undefined"
typeof null; // "object" (a known quirk)
typeof {}; // "object"
typeof []; // "object"
typeof function(){}; // "function"
9. What is the difference between null and undefined?
undefined means a variable has been declared but not assigned a value. null is an intentional absence of value, typically assigned by the developer.
10. What is NaN?
NaN stands for "Not-a-Number" and represents an invalid numeric operation. It is the only value not equal to itself.
console.log(NaN === NaN); // false
console.log(isNaN("hello")); // true
console.log(Number.isNaN("hello")); // false
Functions and Scope
11. What is a closure?
A closure is a function that retains access to variables from its lexical scope, even when called outside that scope.
function counter() {
let count = 0;
return function() {
count++;
return count;
};
}
const increment = counter();
console.log(increment()); // 1
console.log(increment()); // 2
12. What is the difference between function declaration and function expression?
// Function declaration - hoisted
greet();
function greet() { console.log("Hi"); }
// Function expression - not hoisted
const sayHi = function() { console.log("Hi"); };
13. What are arrow functions?
Arrow functions provide a concise syntax and lexically bind this. They cannot be used as constructors and lack their own arguments object.
const add = (a, b) => a + b;
const square = x => x * x;
const greet = () => "Hello";
14. What is the this keyword?
this refers to the object that is executing the current function. Its value depends on how the function is called: method invocation, function invocation, constructor invocation, or arrow function context.
const obj = {
name: "Alice",
greet() { console.log(this.name); }
};
obj.greet(); // "Alice"
const fn = obj.greet;
fn(); // undefined (in strict mode)
15. What is the difference between call, apply, and bind?
function greet(greeting) {
console.log(`${greeting}, ${this.name}`);
}
const user = { name: "Bob" };
greet.call(user, "Hi"); // "Hi, Bob"
greet.apply(user, ["Hi"]); // "Hi, Bob"
const bound = greet.bind(user, "Hi");
bound(); // "Hi, Bob"
call and apply invoke immediately with comma-separated or array arguments. bind returns a new function with a permanently bound this.
16. What is an IIFE?
An Immediately Invoked Function Expression runs as soon as it is defined, creating a private scope.
(function() {
const privateVar = "hidden";
console.log("Executed immediately");
})();
17. What is a callback function?
A callback is a function passed as an argument to another function, executed later — often after an asynchronous operation completes.
function fetchData(callback) {
setTimeout(() => callback("Data loaded"), 1000);
}
fetchData(data => console.log(data));
18. What is a higher-order function?
A higher-order function takes one or more functions as arguments or returns a function. Examples include map, filter, reduce, and custom function composers.
19. What is currying?
Currying transforms a function with multiple arguments into a sequence of functions, each taking a single argument.
const multiply = a => b => c => a * b * c;
console.log(multiply(2)(3)(4)); // 24
20. What is the scope chain?
When a variable is referenced, JavaScript looks for it in the current scope, then outer scopes, up to the global scope. This hierarchy is the scope chain.
Arrays and Objects
21. How do you remove duplicates from an array?
const arr = [1, 2, 2, 3, 4, 4, 5];
const unique = [...new Set(arr)];
console.log(unique); // [1, 2, 3, 4, 5]
22. What is the difference between map and forEach?
map returns a new array and does not mutate the original. forEach executes a function on each element but returns undefined.
23. How does reduce work?
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 10
24. What is the spread operator?
The spread operator (...) expands iterables into individual elements, useful for copying arrays, merging objects, and passing arguments.
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4];
const obj1 = { a: 1 };
const obj2 = { ...obj1, b: 2 };
25. What is destructuring?
const { name, age } = { name: "Alice", age: 25 };
const [first, second] = [10, 20];
function greet({ name }) { console.log(name); }
26. What is the difference between shallow and deep copy?
A shallow copy duplicates the top-level structure but nested objects are still referenced. A deep copy recursively duplicates all nested values.
const original = { a: 1, nested: { b: 2 } };
const shallow = { ...original };
shallow.nested.b = 99;
console.log(original.nested.b); // 99 (shared reference)
const deep = JSON.parse(JSON.stringify(original));
deep.nested.b = 5;
console.log(original.nested.b); // 99 (independent)
27. How do you check if an object has a property?
const obj = { name: "Alice" };
console.log("name" in obj); // true
console.log(obj.hasOwnProperty("name")); // true
console.log(obj.name !== undefined); // true
28. What is the difference between Object.keys, Object.values, and Object.entries?
const obj = { a: 1, b: 2 };
console.log(Object.keys(obj)); // ["a", "b"]
console.log(Object.values(obj)); // [1, 2]
console.log(Object.entries(obj)); // [["a", 1], ["b", 2]]
29. How do you merge two objects?
const merged = { ...obj1, ...obj2 };
// or
const merged2 = Object.assign({}, obj1, obj2);
30. What is JSON and how do you use it in JavaScript?
JSON (JavaScript Object Notation) is a lightweight data interchange format. Use JSON.stringify to convert objects to strings and JSON.parse to convert strings back to objects.
Asynchronous JavaScript
31. What is the event loop?
The event loop is the mechanism that allows JavaScript to perform non-blocking operations by processing the call stack and task queues. It continuously checks if the stack is empty and pushes callbacks from the microtask and macrotask queues.
32. What is a Promise?
A Promise represents the eventual result of an asynchronous operation. It has three states: pending, fulfilled, or rejected.
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Done"), 1000);
});
promise.then(result => console.log(result));
33. What is async/await?
Async/await is syntactic sugar over Promises, making asynchronous code look synchronous and easier to read.
async function fetchData() {
try {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
34. What is the difference between Promise.all and Promise.race?
Promise.all resolves when all promises resolve, and rejects if any one fails. Promise.race resolves or rejects as soon as the first promise settles.
35. What are microtasks vs macrotasks?
Microtasks (Promise callbacks, queueMicrotask) run after the current task and before the next macrotask. Macrotasks (setTimeout, setInterval, I/O) are processed by the event loop after microtasks complete.
36. What is setTimeout?
setTimeout schedules a callback to run after a specified delay. It does not guarantee exact timing because the event loop may be busy.
console.log("1");
setTimeout(() => console.log("2"), 0);
console.log("3");
// Output: 1, 3, 2
37. What is the difference between setTimeout and setInterval?
setTimeout runs a callback once after a delay. setInterval runs a callback repeatedly at the specified interval until cleared with clearInterval.
DOM and Browser APIs
38. What is the DOM?
The Document Object Model is a tree-like representation of an HTML document. JavaScript can manipulate the DOM to update content, styles, and structure dynamically.
39. How do you select elements in the DOM?
document.getElementById("myId");
document.getElementsByClassName("myClass");
document.querySelector(".myClass");
document.querySelectorAll("div");
40. What is event delegation?
Event delegation uses a single listener on a parent element to handle events from its children, leveraging event bubbling. It improves performance and handles dynamically added elements.
document.querySelector("#list").addEventListener("click", e => {
if (e.target.tagName === "LI") {
console.log(e.target.textContent);
}
});
41. What is event bubbling and capturing?
Event bubbling propagates events from the target up to ancestors. Capturing (trickling) propagates from ancestors down to the target. Use the third argument of addEventListener to control this.
42. What is the difference between preventDefault and stopPropagation?
preventDefault stops the default browser action (like form submission). stopPropagation stops the event from bubbling up the DOM.
43. What is localStorage vs sessionStorage vs cookies?
localStorage: persists until explicitly cleared, ~5MB capacity.sessionStorage: cleared when the tab closes, ~5MB capacity.- Cookies: sent with HTTP requests, ~4KB capacity, with expiration.
Object-Oriented JavaScript
44. What is prototypal inheritance?
JavaScript objects inherit properties and methods through a prototype chain. Each object has an internal [[Prototype]] linking to another object.
const animal = { eat() { console.log("eating"); } };
const dog = Object.create(animal);
dog.bark = function() { console.log("bark"); };
dog.eat(); // "eating"
45. What are ES6 classes?
ES6 classes are syntactic sugar over prototype-based inheritance, providing a cleaner syntax for creating objects and handling inheritance.
class Animal {
constructor(name) { this.name = name; }
speak() { console.log(`${this.name} makes a sound`); }
}
class Dog extends Animal {
speak() { console.log(`${this.name} barks`); }
}
const d = new Dog("Rex");
d.speak(); // "Rex barks"
46. What is the difference between classical and prototypal inheritance?
Classical inheritance uses classes and creates rigid hierarchies. Prototypal inheritance uses objects directly, allowing dynamic delegation and easier composition.
Best Practices and Modern JavaScript
47. What is strict mode?
Strict mode ("use strict") enforces stricter parsing and error handling, catching common mistakes like undeclared variables and duplicate parameter names.
48. What are template literals?
const name = "Alice";
const greeting = `Hello, ${name}!
You are ${2024 - 2000} years old.`;
49. What are default parameters and rest/spread operators?
function greet(name = "Guest") { console.log(name); }
function sum(...nums) { return nums.reduce((a, b) => a + b, 0); }
console.log(sum(1, 2, 3, 4)); // 10
50. What are common JavaScript best practices?
- Use
constby default;letonly when reassigning. - Prefer
===over==to avoid type coercion bugs. - Use descriptive variable and function names.
- Handle errors with try/catch in async code.
- Avoid polluting the global scope; use modules.
- Write pure functions where possible for testability.
- Use arrow functions for short callbacks, regular functions for methods.
- Document complex logic with comments.
- Lint your code with ESLint and format with Prettier.
- Write unit tests for critical business logic.
Conclusion
Mastering these 50 JavaScript interview questions gives you a strong foundation for entry-level roles. Focus not just on memorizing answers, but on understanding the underlying concepts — how scope works, why closures matter, how the event loop processes tasks, and when to use modern syntax like arrow functions and async/await. Practice writing the code examples by hand, build small projects that exercise these concepts, and review your answers aloud to simulate the interview experience. With consistent preparation and a clear understanding of fundamentals, you'll walk into your next JavaScript interview ready to demonstrate both knowledge and practical skill.