25+ Top JavaScript Interview Questions and Answers For Beginners
A comprehensive list of important JavaScript Interview Questions and Answers for Beginners with a detailed explanation of the applied JavaScript concept for in-depth understanding.
Anuj Sharma
Last Updated Feb 6, 2026

Practising JavaScript questions is essential to Ace the frontend JavaScript interview round. This comprehensive guide will help you go through important JavaScript interview questions and answers with explanations to solidify your understanding of the core concepts behind these JavaScript interview questions.
25+ JavaScript Interview Questions and Answers - For Beginners
Here is the list of JavaScript questions and answers, along with the explanation
Let's Jump directly to the questions
- What are the different ways to create an object in JavaScript?
- What is the difference between DOM & BOM in JavaScript?
- What is Hoisting in JavaScript, and how does variable and function hoisting work?
- What's the difference between declaring variables using Var, let, and const?
- Explain the event loop in JavaScript and how it works.
- Is JavaScript single-threaded or multi-threaded? Explain why
- What is closure in JavaScript? Explain with an example.
- What is currying in JavaScript? Explain the use case with an example
- What is the difference between setTimeout and setInterval in JavaScript?
- What is "this" keyword in JavaScript? Explain with examples.
- What is Promise in JavaScript, and why Promise is required? Explain with an example
- What is the difference between event bubbling and event capturing?
- Explain Event delegation in JavaScript
- What is the purpose of using stopPropogation()
- What is the difference between "freeze" and "seal" an object?
- What is the Difference between == vs === ?
- What is prototypal inheritance in JavaScript?
- Write an inheritance example using a constructor function (ES5) and using Class (ES6)
- Difference between an arrow function and a normal function in JavaScript?
- How to create an object clone in JavaScript?
- Why are functions called first-class citizens in JavaScript?
- Difference between call, apply and bind
- What is the difference between the following object creation code
- What is the difference between localStorage vs sessionStorage?
- What is the difference between <script/>, <script async /> and <script defer />?
- What is the prototype chain, and how does it work?
Q1. What are the different ways to create an object in JavaScript?
Answer:
There are 5 major ways to create an object in JavaScript
- Using Object Literal - In this way, you can use
{ }to create an object and add key-value properties. This Internally{}is an instance ofObjectonly.
const person = { name: "Anuj", age: 33 }; console.log(person.name); // Output: Anuj console.log({} instanceof Object) // true -
Using new Object() - An Object can be created using the Object class. A new object can be created using by instantiating of Object class.
const person = new Object(); person.name = "Anuj"; person.age = 30; console.log(person.age); // Output: 30 - Using the Constructor function - A new object can be created using a custom construction function. This is similar to a function call, but when you create an object using the new keyword, it makes a this keyword internally and attaches all the properties in the constructor function and returns that this keyword.
function Person(name, age) { this.name = name; this.age = age; } const person1 = new Person("Anuj", 33); console.log(person1.name); // Output: Anuj - Using Object.create() - An object can be created using the create function of object.
const animal = { eats: true }; const cat = Object.create(animal); cat.sound = "maoww"; console.log(cat.eats); // Output: true (inherited) console.log(dog.sound); // Output: "maoww" - Using ES6 class Syntax - This is another way to use ES6 class and create an object using a class constructor, even though this is just a syntactic sugar on top of the constructor and object creation using a constructor function
class Car { constructor(brand) { this.brand = brand; } } const myCar = new Car("BMW"); console.log(myCar.brand); // Output: BMW
Q2. What is the difference between DOM & BOM in JavaScript?
Answer:
Here is the difference between DOM and BOM based on purpose & use case.
DOM - Document Object Modal
- Purpose - DOM represents the element (HTML elements) structure which constructs the webpage
- Use case - Its primary use is to change the content, structure, and style of web pages.
- Examples - Document object, getElementById, etc
BOM - Browser Object Modal
- Purpose - BOM represents the browser functions which the browser takes care of outside the webpage
- Use case - Its primary use is to interact with the browser-level features
- Example objects - setTimeout(), setInterval, alert, confirm, etc.
Q3. What is Hoisting in JavaScript, and how does variable and function hoisting work?
Answer:
In simple terms, Hoisting is JavaScript’s behavior of moving declarations to the top (In simple terms to understand) of the current scope before code execution. Here are the examples for variable and function hoisting in JavaScript,
- Function hoisting in JavaScript - In this case, even though the function definition is below the execution but when the JavaScript interpreter interprets the code, it declares the function definition at the start of the scope, and that's why JavaScript already know about the function
sayHelloeven before its definition.
sayHello(); // Output: Hello! function sayHello() { console.log("Hello!"); } - Hoisting of
var- Similar to JavaScript functions, the JavaScript engine adds the declaration (with undefined) of thevaron top of the scope while interpretation, and that's why the JavaScript engine already found the variable a in the scope with value - undefined, and that's why it printed undefined.
console.log(a); // Output: undefined var a = 10; - Hoisting of
let&const- Technicallyletandconstare hoisted, but they are in a "temporal dead zone" and can't be accessed before they are defined.
console.log(b); // ReferenceError: b is not defined let b = 5;
š”Learn more about hoisting
Q4. What's the difference between declaring variables using Var, let, and const?
Answer:
Declaration using var
- Function-scoped: Accessible within the function where it is declared.
- Hoisted and initialised as "undefined".
function demoVar() {
console.log(x); // undefined, hoisted
var x = 10;
console.log(x); // 10
}
demoVar();
Declaration using let
- Block-scoped: Only available inside the block (
{}) where it is defined. - It can be updated, but not redeclared in the same scope.
- Hoisted, but not initialized, stays in "Temporal Dead Zone".
function demoLet() {
console.log(y); // ReferenceError
let y = 20;
console.log(y); // 20
}
demoLet();
Declaration using const
- Block-scoped, just like
let. - Cannot be updated or redeclared (value must stay the same).
- Must be initialized during declaration.
const z = 30;
z = 40; // Error: Assignment to constant variable
console.log(z); // 30
Q5. Explain the event loop in JavaScript and how it works? (Need changes)
Answer:
JavaScript is single-threaded, but can handle asynchronous tasks using the event loop. Event loop is the part of the javascript engine which continously loop through to move tasks from Microtask(Promises) and MacroTask(setTimeout, setInterval) queues to the Call Stack for the execution.
Note: Immediately after every macrotask, the event loop move all tasks from microtask queue to the javascript call stack for execution, prior to running any other macrotasks or rendering or anything else.
š Here's how it works:
-
JavaScript Engine has a Call Stack to execute the code instructions. from LIFO (last In, First Out) fashion.
-
Browser's Web APIs handle things like
setTimeout, AJAX, etc. -
There are MicroTask and MacroTask Queues which handles promises and WebAPIs. It waits to push tasks to the call stack when empty.
-
The Event Loop keeps checking if the stack is empty — if so, it takes tasks from the queue and runs them.
console.log("Start");
setTimeout(() => {
console.log("Timeout");
}, 0);
console.log("End");
// Output
Start
End
Timeout
Note: Even though setTimeout has 0ms delay, it goes to the task queue and runs after the synchronous code finishes.
Q6. Is JavaScript single-threaded or multi-threaded?
Answer:
"JavaScript is Single-Threaded", meaning it has one call stack, and it can only execute one code instructions at a time. JavaScript can support asynchronus tasks becuase of the event loop and browser APIs.
Q7. What is closure in JavaScript? Explain with an example.
Answer:
A closure is when a function remembers the variables from its outer scope, even after that outer function has finished running.
function outer() {
let count = 0;
function inner() {
count++;
console.log(count);
}
return inner;
}
const counter = outer(); // outer runs and returns inner
counter(); // 1
counter(); // 2
counter(); // 3
Even though outer() is done executing, the inner() function still remembers the variable count. That’s a closure!
Why Closures are Useful:
- Data privacy (hide variables).
- Factory design pattern.
- Maintaining state across function calls.
Q8. What is currying in JavaScript? Explain the use case with an example
Answer:
Currying is a technique of transforming a function with multiple arguments into a sequence of functions, each taking a single argument. Currying is use-ful to provide partial application where some of the application already build but new functionalities can be build on top of the existing applicaiton.
Use case: Primary use case of the Currying is implementation of "Partial application" which can be run independently or along with the other independent other applications.
// Normal function
function add(a, b) {
return a + b;
}
// Curried version
function curryAdd(a) {
return function(b) {
return a + b;
};
}
console.log(curryAdd(2)(3)); // 5
// Use case: create partial function
const add5 = curryAdd(5);
console.log(add5(10)); // 15
Q9. What is the difference between setTimeout and setInterval in JavaScript?
Answer:
| Feature | setTimeout |
setInterval |
|---|---|---|
| Runs | Run once after the input delay | Runs repeatedly on given Interval |
| Usage | Delayed execution | Repeated execution at intervals |
setTimeout(() => {
console.log("Runs once after 1s");
}, 1000);
setInterval(() => {
console.log("Runs every 1s");
}, 1000);
Q10. What is "this" keyword in JavaScript? Explain with examples.
Answer:
this refers to the object that is executing the current function. Its value depends on the context.
- Global Context - window (in browser)
- Object method - belongs to the object, which calls the object method
- Arrow function - this contains the lexical scope of the parant of arrow function.
// Global context (browser)
console.log(this); // window
// Object method
const user = {
name: "Anuj",
greet() {
console.log("Hello", this.name); // 'this' refers to user
}
};
user.greet(); // Hello Anuj
// Arrow function (lexical `this`)
const obj = {
value: 10,
show: () => {
console.log(this.value); // undefined (arrow doesn't bind `this`)
}
};
obj.show();
More references
Q11. What is Promise in JavaScript, and why Promise is required? Explain with an example
Answer:
A Promise is a JavaScript object that represents the future result of an asynchronous operation, before promise code requires the callback hell in order to execute the callback code.
ā What are the benifits of using Promises?
- Handle asynchronous tasks like API calls
- Avoid callback hell in the code
- Provide a better error handling machanism in case of failure in asynchronous execution.
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received");
}, 1000);
});
};
fetchData()
.then((data) => console.log(data)) // "Data received"
.catch((err) => console.error(err));
Async-Await can also be used for the asynchornousn task handling which has been developed on top of the promise to provide a functionality where async code can be executed similar to the synchronos code, execution halts untill await function returns the result.
async function fetchUserData() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
const user = await response.json();
console.log("User:", user.name);
} catch (error) {
console.error("Error fetching user:", error);
}
}
fetchUserData();
Q12. What is the difference between event bubbling and event capturing?
Answer:
Bubbling and capturing both are phases in the DOM event propagation model. In the capturing phase, event propogation happens from child to parent, but in capturing phase event propogation happened from Parent to Child elements.
| Feature | Bubbling | Capturing |
|---|---|---|
| Direction | Child → Parent | Parent → Child |
| Default Behavior | ā Yes | ā Only with { capture: true }In addEventListener function. |
// Bubbling
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent bubbling");
});
// Capturing
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent capturing");
}, true);
Q13. Explain Event delegation in JavaScript
Answer:
Event delegation is when a parent element handles events for its child elements using a single event listener.
ā Why use it?
- Better performance (fewer listeners)
- Dynamically handle new elements
<ul id="todo-list">
<li>Buy milk</li>
<li>Walk dog</li>
</ul>
<button id="add">Add New Item</button>
const list = document.getElementById("todo-list");
const addBtn = document.getElementById("add");
// Event Delegation: single listener on parent
list.addEventListener("click", (event) => {
if (event.target.tagName === "LI") {
alert(`You clicked: ${event.target.textContent}`);
}
});
// Dynamically add new items
addBtn.addEventListener("click", () => {
const newItem = document.createElement("li");
newItem.textContent = "New Task " + Math.floor(Math.random() * 100);
list.appendChild(newItem);
});
Q14. What is the difference between stopPropogation() vs preventDefault()?
Answer:
| Method | Purpose |
|---|---|
stopPropagation() |
Stops event from bubbling/capturing |
preventDefault() |
Stops the default action of the element |
document.querySelector("a").addEventListener("click", function (e) {
e.preventDefault(); // stops link navigation
e.stopPropagation(); // stops event bubbling
console.log("Click handled");
});
Q15. What is the difference between "freeze" and "seal" an object?
Answer:
| Feature | Object.freeze() |
Object.seal() |
|---|---|---|
| Add properties | ā No | ā No |
| Modify values | ā No | ā Yes |
| Delete props | ā No | ā No |
| Configurable | ā No | ā No |
const frozen = Object.freeze({ a: 1 });
frozen.a = 2; // ā fails silently
const sealed = Object.seal({ a: 1 });
sealed.a = 2; // ā
works
delete sealed.a; // ā fails
Q16. What is the Difference between == vs === ?
| Operator | Name | Checks |
|---|---|---|
== |
Loose equality | Values after type coercion |
=== |
Strict equality | Values and types both |
console.log(5 == "5"); // true (coerced)
console.log(5 === "5"); // false (different types)
Note: Prefer === in real-world code for type safety.
Q17. What is prototypal inheritance in JavaScript?
Answer:
Prototypal inheritance is a feature in JavaScript where objects can inherit properties and methods from their parent object using the [[Prototype]] chain. Every JavaScript object has an internal link to its parent object called its prototype, and it can delegate behavior (methods/properties) to that prototype. This allows reusability and shared behaviour across objects. Here is the example
const animal = {
eats: true,
walk() {
console.log("Animal walks");
}
};
const dog = Object.create(animal); // dog inherits from animal
dog.barks = true;
console.log(dog.eats); // true (inherited)
dog.walk(); // Animal walks
Q18. Write an inheritance in JavaScript example using a constructor function (ES5) and using Class (ES6)
Answer:
Inheritance in JavaScript using Constructor Function (ES5)
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function () {
console.log(`${this.name} makes a noise.`);
};
function Dog(name) {
Animal.call(this, name); // call parent constructor
}
Dog.prototype = Object.create(Animal.prototype); // inherit prototype
Dog.prototype.constructor = Dog;
const dog = new Dog("Moti");
dog.speak(); // Moti makes a noise.
Inheritance in JavaScript using Class (ES6)
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
constructor(name) {
super(name); // call parent constructor
}
}
const dog = new Dog("Moti");
dog.speak(); // Moti makes a noise.
Q19. Difference between an arrow function and a normal function in JavaScript?
Answer:
| Feature | Arrow Function | Normal Function |
|---|---|---|
this Scope |
Lexical scope (inherits from parent scope) |
Dynamic Scoping (depends on how called) |
| Constructor usage | ā Can't be used as constructor | ā
Can use new keyword |
| arguments object | ā Not available | ā Available |
Here is the example
const obj = {
value: 10,
regularFn: function () {
console.log("Regular:", this.value);
},
arrowFn: () => {
console.log("Arrow:", this.value); // this -> Parent Laxical scope
}
};
obj.regularFn(); // Regular: 10
obj.arrowFn(); // Arrow: undefined
Q20. How to create object's "Deep clone" and "Shallow clone" in JavaScript?
Answer:
Here are the ways to create Shallow and Deep clone in JavaScript :
Shallow Clone in JavaScript
- Shallow clone using Object.create()
const original = { a: 1, b: 2 }; const clone = Object.assign({}, original); - Shallow clone using Spread Operator(...)
const original = {name: 'Anuj', lastname: 'Sharma'} const clone = { ...original };
Deep clone in JavaScript
- Deep clone in JavaScript using
const original = { name: 'Anuj', lastname: 'Sharma', address: { pin: 411057 } } const deepClone = structuredClone(original);
Q21. Why are functions called first-class citizens in JavaScript?
Answer:
Functions can be used in the most versatile ways in JavaScript, and all the constructs can be defined as functions, for example
- Functions can be assigned to the variables.
- Functions can be passed as part of the function parameters, and functions can also be returned from the function.
- Functions can be defined as Classes in the form of Constructor Functions, which can be used to create objects
Q22. Difference between call, apply and bind
Answer:
| Method | Calls function immediately | Arguments passed | Returns |
|---|---|---|---|
call Fn.call(a,b,c) |
ā Yes | Individually like general parameter | Return value of function |
apply Fn.apply([a,b,c]) |
ā Yes | Array | Return value of function |
bind Fn.bind(context) |
ā No (returns a new function) | Individually like general parameter | New function, bounded with context passed. |
Examples
function greet(greeting, lastname) {
console.log(`${greeting}, ${this.name} ${lastname}`);
}
const person = { name: "Anuj" };
// Call
greet.call(person, "Hello", "Sharma"); // Hello, Anuj Sharma
// Apply
greet.apply(person, ["Hi", "Sharma"]); // Hi, Anuj Sharma
// Bind
const boundGreet = greet.bind(person, "Hey", " Sharma");
boundGreet(); // Hey, Anuj Sharma
Checkout polyfills to learn more
Q23. What is prototype chaining in JavaScript? Explain with examples
Answer:
Prototype chaining is a way JavaScript enables inheritance. Every object has an internal link (__proto__) to its prototype, forming a chain. When you try to access a property, JavaScript looks up the parent chain until it finds it or hits null.
const animal = {
eats: true
};
const dog = {
barks: true
// __proto__: animal <- This can be assigned like this
};
// Prototype chain
Object.setPrototypeOf(dog, animal)
console.log(dog.barks); // true
console.log(dog.eats); // true (inherited from animal)
Q24. What is the difference between localStorage vs sessionStorage?
Answer:
Browser provides localstorage & sessionstorage to store the key-values.
| Feature | localStorage |
sessionStorage |
|---|---|---|
| Lifespan | Until manually cleared | Until browser/tab is closed |
| Scope | Shared across tabs/windows | Only in current tab/window |
| Capacity | ~5–10MB | ~5MB |
Here is the example
localStorage.setItem("token", "abc123");
sessionStorage.setItem("user", "Anuj");
console.log(localStorage.getItem("token")); // "abc123"
console.log(sessionStorage.getItem("user")); // "Anuj"
Q25. What is the difference between <script />, <script async /> and <script defer />?
Answer:
| Tag Type | Blocks HTML parsing? | When script runs? | Execution Order |
|---|---|---|---|
<script> |
ā Yes | Immediately after download | In order |
<script async> |
ā No | As soon as downloaded (out of order) | ā No guarantee |
<script defer> |
ā No | After HTML is fully parsed | ā In order |
Example
<script src="sync.js"></script>
<script async src="async_script.js"></script>
<script defer src="defer_script.js"></script>
Q26. What are the different ways to merge two objects in JavaScript?
Answer:
Here are the 2 ways to merge objects
- Using Object.merge() method - It shallow merges the objects
const obj1 = { a: 1 }; const obj2 = { b: 2 }; const merged = Object.assign({}, obj1, obj2); console.log(merged); // { a: 1, b: 2 } - Using ES6 object spreading - It also shallow merges one or more objects
const obj1 = { a: 1, b: 2 }; const obj2 = { b: 3, c: 4 }; const merged = { ...obj1, ...obj2 }; console.log(merged); // { a: 1, b: 3, c: 4 }
Note: Since both the above options provide shallow merging, if there is a specific requirement to merge complex objects, we can either create a custom recursive solution or use the lodash merge function.
Other Resources
A seasoned Sr. Engineering Manager at GoDaddy (Ex-Dell) with over 12+ years of experience in the frontend technologies. A frontend tech enthusiast passionate building SaaS application to solve problem. Know more about me š
Learn Next
Comments
Be the first to share your thoughts!
No comments yet.
Start the conversation!
Share your expertise
Publish a blog or quick notes on topics you know well ā your write-up could be the answer someone needs before their next frontend interview.
Build your portfolio
Help the community
Sharpen your skills
Earn goodies
Other Related Blogs
React Hook Rules: Why hooks declarations are not allowed inside functions
Frontendgeek
Last Updated Feb 6, 2026
A quick guide to explain an important react interview question, why React Hooks declarations are not allowed inside functions or any conditional blocks with code example.
Implementing a stopwatch using React - Frontend Machine Coding Question
Pallavi Gupta
Last Updated Feb 21, 2026
Concise explanation of stopwatch implementation using React, it involves the usage of useEffect hook for creating a stopwatch and tracking milliseconds.
Implement useClickOutside() custom Hook in React [Interview]
Anuj Sharma
Last Updated Dec 23, 2025
Understand the implementation of useClickOutside() custom hook in react and how it can be used to implement Modal like functionality.
Best Frontend System Design Interview Cheat Sheet š
Anuj Sharma
Last Updated Jun 9, 2026
A Comprehensive Frontend System Design Cheat Sheet helps you approach the Frontend System Design Interview in the most structured way and covers the 7 most important Frontend System Design Topics.
