This Top 60+ JavaScript Questions list is perfect for interview preparation, coding practice, and strengthening your core concepts. By mastering these questions, you can confidently tackle JavaScript interviews and build powerful applications.
JavaScript is a high-level, interpreted programming language that is primarily used to make web pages interactive and dynamic. It allows developers to create functionalities like button clicks, form validation, animations, DOM manipulation, and API calls. JavaScript can run on both the client-side (browser) and server-side (Node.js), making it a versatile language for full-stack development.
Key Points:
- Runs in the browser without installation.
- Supports object-oriented, functional, and event-driven
programming.
- Enables dynamic content updates without reloading the page.
- Works with HTML and CSS to create modern web applications.
JavaScript provides two types of data types:
1. Primitive (Value Type):
These store actual values and are stored in stack memory. Each variable gets its
own separate memory.
(Examples: string, number, boolean, null, undefined, bigint)
2. Non-Primitive (Reference Type):
These store reference (address) in stack but actual data is stored in heap
memory. Multiple variables can point to the same data.
(Examples: object, array, function)
var: var is function-scoped and can be
re-assigned and redeclared. It is the older way to declare variables.
let: let is block-scoped and can be re-assigned, but cannot
be redeclared in the same scope. It is the modern way to declare
variables.
const: const is block-scoped and
cannot be re-assigned or redeclared. It is used for constant values.
Example:
5 == "5" → true (value is same, type is converted)
5 === "5" → false (value is same, but type is different)
Hoisting means JavaScript moves variable and function declarations to the top of their scope before running the code. This allows you to use functions and variables even before they are declared.
Example:
console.log(a); // undefined
var a = 5; // The declaration 'var a' is hoisted, but value is assigned later
A function is a block of code used to perform a specific task.
Example:
function greet() { console.log("Hello"); }
An array stores multiple values in a single variable.
Example:
let arr = [1, 2, 3];
An object stores data in key-value pairs.
Example:
let user = { name: "Pranav", age: 20 };
In JavaScript:
undefined means a variable has been declared but no value
is assigned to it.
null means the variable is intentionally set to have no
value.
Example:
let x;
console.log(x); // undefined
let y = null;
console.log(y); // null
Arrow functions are a short way to write functions.
Example:
const add = (a, b) => a + b;
Function scope means variables declared inside a function are only accessible within that function. They cannot be accessed outside the function.
Example:
function test() {
let x = 10;
console.log(x); // 10
}
console.log(x); // Error: x is not defined
Block scope means variables declared inside a block (like inside
{ }) using let or const are only accessible
inside that block.
Example:
if(true) {
let y = 20;
console.log(y); // 20
}
console.log(y); // Error: y is not defined
Global scope means variables declared outside any function or block are accessible from anywhere in the code.
Example:
let z = 30; // global variable
function show() {
console.log(z); // 30
}
console.log(z); // 30
Function Declaration: Defined with function keyword,
hoisted to the top of scope.
Function Expression: Function assigned to a variable, not hoisted.
Example:
// Declaration
function greet() { console.log("Hi"); }
greet(); // Hi
// Expression
const greet2 = function() { console.log("Hello"); };
greet2(); // Hello
A closure is a function that remembers variables from its outer scope even after the outer function has finished executing.
Example:
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2
Lexical scope means inner functions can access variables from their outer functions, based on where the function is written in the code.
Example:
function outer() {
let name = "Pranav";
function inner() {
console.log(name); // Pranav
}
inner();
}
outer();
IIFE (Immediately Invoked Function Expression) is a function that runs immediately after it is defined.
Example:
(function() {
console.log("Runs immediately!");
})();
A callback function is a function passed as an argument to another function and executed later.
Example:
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
greet("Pranav", function() { console.log("Callback executed!"); });
- call: Calls a function with a given `this` and arguments
separately.
- apply: Calls a function with a given `this` and arguments as an
array.
- bind: Returns a new function with bound `this`.
Example:
function greet(city) { console.log(this.name + " from " + city); }
let user = { name: "Pranav" };
greet.call(user, "Surat"); // Pranav from Surat
greet.apply(user, ["Surat"]); // Pranav from Surat
let greetUser = greet.bind(user);
greetUser("Surat"); // Pranav from Surat
Recursion is when a function calls itself to solve a problem, usually with a base condition to stop.
Example:
function factorial(n) {
if(n === 0) return 1;
return n * factorial(n-1);
}
console.log(factorial(5)); // 120
An object is a collection of key-value pairs that stores related data and functionality. Keys are strings (or symbols) and values can be any data type, including other objects or functions.
Example:
let user = {
name: "Pranav",
age: 20,
greet: function() {
console.log("Hello " + this.name);
}
};
console.log(user.name); // Pranav
user.greet(); // Hello Pranav
An array is an ordered list of values stored in a single variable. Arrays can hold different data types, including numbers, strings, objects, or even other arrays.
Example:
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0]); // Apple
You can loop through an array using for, for...of, forEach loops.
Example:
let numbers = [1, 2, 3, 4];
// Using for loop
for(let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
// Using for...of
for(let num of numbers) {
console.log(num);
}
// Using forEach
numbers.forEach(num => console.log(num));
You can loop through an object using for...in loop.
Example:
let user = { name: "Pranav", age: 20 };
for(let key in user) {
console.log(key + ": " + user[key]);
}
// Output:
// name: Pranav
// age: 20
Object methods are functions that are stored as object properties and can perform actions using the object data.
Example:
let user = {
name: "Pranav",
greet: function() {
console.log("Hello " + this.name);
}
};
user.greet(); // Hello Pranav
Shallow copy: Copies only the first level, nested objects are
shared.
Deep copy: Copies all levels, including nested objects, creating a
new independent object.
Example:
let obj = { a: 1, b: { c: 2 } };
let shallow = { ...obj }; // nested b is shared
let deep = JSON.parse(JSON.stringify(obj)); // full deep copy
The spread operator (...) allows you to expand arrays or objects into individual elements or key-value pairs.
Example:
let arr1 = [1, 2];
let arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]
let obj1 = { a: 1 };
let obj2 = { ...obj1, b: 2 }; // { a: 1, b: 2 }
Array destructuring allows extracting values from arrays into individual variables easily.
Example:
let arr = [1, 2, 3];
let [a, b, c] = arr;
console.log(a, b, c); // 1 2 3
Object destructuring allows extracting values from objects into variables based on keys.
Example:
let user = { name: "Pranav", age: 20 };
let { name, age } = user;
console.log(name, age); // Pranav 20
You can merge objects using spread operator and arrays using concat or spread operator.
Example:
// Merge arrays
let arr1 = [1, 2];
let arr2 = [3, 4];
let mergedArr = [...arr1, ...arr2]; // [1,2,3,4]
// Merge objects
let obj1 = { a: 1 };
let obj2 = { b: 2 };
let mergedObj = { ...obj1, ...obj2 }; // { a:1, b:2 }
Asynchronous JavaScript allows code to run without blocking the execution of other code. It is useful for tasks like API calls, timers, and reading files.
Example:
console.log("Start");
setTimeout(() => console.log("Async Task"), 1000);
console.log("End");
// Output:
// Start
// End
// Async Task (after 1 second)
The event loop is a mechanism that allows JavaScript to handle asynchronous operations while maintaining a single-threaded execution.
Example:
console.log("Start");
setTimeout(() => console.log("Timer"), 0);
console.log("End");
// Output:
// Start
// End
// Timer
A Promise is an object representing the eventual completion or failure of an asynchronous operation.
Example:
let promise = new Promise((resolve, reject) => {
let success = true;
if(success) resolve("Done");
else reject("Error");
});
promise.then(msg => console.log(msg)).catch(err => console.log(err));
Synchronous code: Runs line by line, blocking next
statements until complete.
Asynchronous code: Runs without blocking, allowing
other code to execute while waiting for results.
Example:
// Synchronous
console.log("Start");
console.log("End");
// Asynchronous
console.log("Start");
setTimeout(() => console.log("Async"), 1000);
console.log("End");
.then() is used to handle the resolved value of a Promise.
Example:
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
async/await is a syntax that makes asynchronous code look like synchronous code for better readability.
Example:
async function fetchData() {
try {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
console.log(data);
} catch(error) {
console.log(error);
}
}
fetchData();
Promise.all: Waits for all promises to resolve or
reject.
Promise.race: Resolves or rejects as soon as one
promise settles.
The fetch API allows making network requests and handling responses as promises.
Example:
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data));
Errors can be handled using .catch() for promises or try/catch with async/await.
Generators are functions that can pause and resume execution using yield.
Example:
function* gen() {
yield 1;
yield 2;
}
let g = gen();
console.log(g.next().value); // 1
console.log(g.next().value); // 2
The DOM (Document Object Model) is a programming interface that represents the HTML structure of a web page as a tree of objects. JavaScript can interact with the DOM to read, modify, or delete HTML elements and content.
Example:
let heading = document.getElementById("title");
console.log(heading.innerText);
JavaScript provides multiple methods to select elements: getElementById, getElementsByClassName, getElementsByTagName, querySelector, querySelectorAll.
Example:
// By ID
let title = document.getElementById("title");
// By class
let items = document.getElementsByClassName("item");
// Using querySelector
let firstItem = document.querySelector(".item");
You can change content using innerText, innerHTML, or textContent properties.
Example:
let heading = document.getElementById("title");
heading.innerText = "New Title";
heading.innerHTML = "Updated Title";
You can create elements using document.createElement and append them to the DOM using appendChild or append.
Example:
let div = document.createElement("div");
div.innerText = "Hello World!";
document.body.appendChild(div);
Event listeners are functions that wait for specific events (like click, mouseover, input) on elements and execute code when those events occur.
Example:
let btn = document.getElementById("btn");
btn.addEventListener("click", function() {
alert("Button clicked!");
});
Inline events are added directly in HTML attributes (onclick, onmouseover), while addEventListener attaches events via JavaScript, allowing multiple listeners for the same element and better separation of HTML and JS.
Example:
// Inline (HTML)
//
// addEventListener (JS)
btn.addEventListener("click", () => alert("Clicked"));
Event bubbling: Events propagate from the innermost element
to the outer elements.
Event capturing: Events propagate from the outer element to
the inner element.
Example:
parentDiv.addEventListener("click", () => console.log("Parent"), true); // capturing
childDiv.addEventListener("click", () => console.log("Child")); // bubbling
Event delegation is a technique where you attach a single event listener to a parent element to handle events on its child elements dynamically.
Example:
document.getElementById("list").addEventListener("click", function(e) {
if(e.target && e.target.nodeName == "LI") {
console.log("List item clicked: " + e.target.innerText);
}
});
Use event.preventDefault() inside the event handler to prevent the default action of an element (like link navigation or form submission).
Example:
let link = document.querySelector("a");
link.addEventListener("click", function(e) {
e.preventDefault();
console.log("Default navigation prevented");
});
Use event.stopPropagation() inside the event handler to stop the event from bubbling or capturing further.
Example:
childDiv.addEventListener("click", function(e) {
e.stopPropagation();
console.log("Event stopped at child");
});
In JavaScript, every object has a prototype property which is a reference to another object. Prototypes are used to implement inheritance and share methods across objects without duplicating code.
Example:
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log("Hello " + this.name);
};
let p1 = new Person("Pranav");
p1.greet(); // Hello Pranav
Prototypal inheritance allows objects to inherit properties and methods from other objects via the prototype chain.
Example:
let animal = { eats: true };
let rabbit = Object.create(animal);
console.log(rabbit.eats); // true (inherited from animal)
this refers to the context object in which a function is executed. Its value depends on how the function is called.
Example:
const obj = { name: "Pranav", greet() { console.log(this.name); } };
obj.greet(); // Pranav
function test() { console.log(this); }
test(); // window (in browser)
ES6 modules allow you to export and import code (functions, objects, variables) between different JavaScript files, improving code organization and reusability.
Example:
// utils.js
export function add(a, b) { return a + b; }
// main.js
import { add } from './utils.js';
console.log(add(2, 3)); // 5
Symbol is a unique and immutable primitive value used as an identifier for object properties, preventing property name conflicts.
Example:
let id = Symbol("id");
let user = { [id]: 123 };
console.log(user[id]); // 123
WeakMap and WeakSet are special collections that hold weak references to objects, meaning they do not prevent garbage collection.
Example:
let wm = new WeakMap();
let obj = {};
wm.set(obj, "data");
obj = null; // object can be garbage collected
Getters and setters allow you to define methods to get or set object property values while controlling access and adding custom behavior.
Example:
let user = {
firstName: "Pranav",
lastName: "Chavda",
get fullName() { return this.firstName + " " + this.lastName; },
set fullName(name) { [this.firstName, this.lastName] = name.split(" "); }
};
console.log(user.fullName); // Pranav Chavda
user.fullName = "John Doe";
console.log(user.firstName); // John
Generators are special functions that can pause execution and resume later using the yield keyword.
Example:
function* gen() {
yield 1;
yield 2;
yield 3;
}
let g = gen();
console.log(g.next().value); // 1
console.log(g.next().value); // 2
The call stack keeps track of function execution in order, while the task queue stores asynchronous callbacks waiting to be executed after the call stack is empty.
Example: Functions inside setTimeout go to the task queue, not the call stack immediately.
JavaScript automatically manages memory by allocating space for objects and variables, and removing them when they are no longer needed. This process is called garbage collection.
Example: Objects no longer referenced are automatically removed from memory by the JS engine.
Download the complete PDF with all 60 Q&A, code examples, and interview tips. Perfectly formatted for offline study.
No sign-up required · Instant download · 2.1 MB
More questionnaires to sharpen your skills