JavaScript Interview Questions

50 Questions

JS Basics

Q1

What is JavaScript?

JavaScript is a programming language mainly used to make websites interactive and dynamic. It runs inside the browser and helps handle user actions, animations, validations, API calls, and more. Along with HTML and CSS, it forms the core of modern web development. Example: console.log("Hello World");

Q2

What is the difference between var, let, and const?

var is function-scoped and can be redeclared. let is block-scoped and allows value reassignment. const is also block-scoped but its value cannot be reassigned after declaration. Modern JavaScript mainly uses let and const because they avoid many scope-related issues. Example: var a = 10; let b = 20; const c = 30;

Q3

What are data types in JavaScript?

JavaScript supports different data types used to store values. Primitive types include string, number, boolean, null, undefined, bigint, and symbol. Non-primitive types include objects, arrays, and functions. Choosing the correct data type helps manage data efficiently inside applications. Example: let name = "John"; let age = 25; let isStudent = true;

Q4

What is the difference between null and undefined?

undefined means a variable has been declared but no value is assigned yet. null is an intentional empty value assigned by the developer. Both represent absence of data, but undefined comes automatically while null is manually assigned. Example: let a; let b = null;

Q5

What is type coercion in JavaScript?

Type coercion is the automatic conversion of one data type into another during operations or comparisons. JavaScript performs this conversion internally. Sometimes it causes unexpected results, so developers prefer strict comparisons and explicit conversions for better clarity. Example: console.log("5" + 2); // "52" console.log("5" - 2); // 3

Q6

What is the difference between == and ===?

== compares values after type conversion, while === compares both value and data type without conversion. Because strict comparison avoids unexpected behavior, developers usually prefer === in real projects for safer and more predictable conditions. Example: console.log(5 == "5"); // true console.log(5 === "5"); // false

Q7

What are template literals?

Template literals are strings written using backticks instead of quotes. They allow embedding variables and expressions directly using ${} syntax. They also support multi-line strings, making code cleaner and easier to read compared to normal string concatenation. Example: let name = "Sam"; console.log(`Hello ${name}`);

Q8

What are truthy and falsy values?

Truthy values behave like true in conditions, while falsy values behave like false. JavaScript has falsy values such as 0, "", null, undefined, NaN, and false. Every other value is generally considered truthy. Example: if("Hello") { console.log("Truthy"); }

Q9

What is hoisting in JavaScript?

Hoisting is JavaScript's behavior of moving declarations to the top of their scope before execution. Variables declared with var are initialized as undefined, while let and const remain in a temporal dead zone until declaration. Example: console.log(a); var a = 5;

Q10

What is scope in JavaScript?

Scope defines where variables can be accessed in a program. JavaScript mainly has global scope, function scope, and block scope. Proper scope management prevents variable conflicts and helps keep code organized, secure, and easier to maintain. Example: function test() { let x = 10; }

Functions

Q11

What is a function in JavaScript?

A function is a reusable block of code designed to perform a specific task. Functions help reduce repetition, improve readability, and organize logic properly. They can accept parameters, process data, and return values when needed. Example: function greet() { console.log("Hello"); }

Q12

What is the difference between function declaration and function expression?

A function declaration defines a named function and gets hoisted completely. A function expression stores a function inside a variable and is not fully hoisted. Function expressions are commonly used with callbacks and modern JavaScript patterns. Example: function test() {} const demo = function() {};

Q13

What are arrow functions?

Arrow functions are a shorter syntax introduced in ES6 for writing functions. They make code cleaner and automatically inherit this from the surrounding scope. Arrow functions are commonly used in callbacks, array methods, and modern frontend development. Example: const add = (a, b) => a + b;

Q14

What is the difference between regular functions and arrow functions?

Regular functions have their own this keyword, while arrow functions inherit this from the parent scope. Regular functions can be used as constructors, but arrow functions cannot. Arrow functions also provide shorter syntax for writing simple functions. Example: const user = { name: "Alex", show: () => console.log(this) };

Q15

What is a callback function?

A callback function is a function passed as an argument to another function and executed later. Callbacks are commonly used for asynchronous tasks like API calls, timers, and event handling, allowing code execution after a task finishes. Example: function greet(name, callback) { callback(); }

Q16

What are higher-order functions?

Higher-order functions are functions that take another function as an argument or return a function. They help create reusable and flexible logic. Methods like map(), filter(), and reduce() are common examples in JavaScript. Example: const numbers = [1,2,3]; numbers.map(num => num * 2);

Q17

What is a closure in JavaScript?

A closure happens when a function remembers variables from its outer scope even after the outer function has finished executing. Closures are useful for data privacy, maintaining state, and creating functions with persistent memory. Example: function outer() { let count = 0; return function() { count++; }; }

Q18

What is recursion?

Recursion is a technique where a function calls itself repeatedly until a stopping condition is met. It is commonly used for problems involving repetition, tree structures, and mathematical calculations like factorials and Fibonacci sequences. Example: function factorial(n) { return n === 1 ? 1 : n * factorial(n - 1); }

Q19

What is an IIFE?

An IIFE, or Immediately Invoked Function Expression, is a function that runs immediately after being created. It helps avoid polluting the global scope and is useful for creating private variables and isolated code blocks. Example: (function() { console.log("Runs immediately"); })();

Q20

What is the this keyword in JavaScript?

The this keyword refers to the object currently executing the function. Its value depends on how the function is called. In browsers, global this usually refers to the window object. Example: const user = { name: "Sam", show() { console.log(this.name); } };

Arrays & Objects

Q21

What is the difference between arrays and objects?

Arrays store ordered collections of values using indexes, while objects store data as key-value pairs. Arrays are mainly used for lists, whereas objects are better for representing structured information with named properties. Example: let fruits = ["Apple", "Mango"]; let user = {name: "John", age: 25};

Q22

What are array methods in JavaScript?

Array methods are built-in functions used to manipulate arrays easily. Common methods include push(), pop(), map(), filter(), and reduce(). These methods simplify operations like adding items, removing items, transforming data, and searching values. Example: let arr = [1,2,3]; arr.push(4);

Q23

What is the difference between map(), filter(), and reduce()?

map() creates a new array by transforming values. filter() returns elements that match a condition. reduce() combines array values into a single result like sum or object transformation. These methods are heavily used in modern JavaScript development. Example: [1,2,3].map(n => n * 2);

Q24

What is destructuring in JavaScript?

Destructuring is a feature that allows extracting values from arrays or objects into separate variables easily. It makes code cleaner and reduces repetitive property access, especially when handling API responses or large objects. Example: const [a, b] = [1, 2];

Q25

What is the spread operator?

The spread operator (...) expands elements from arrays or objects into individual values. It is commonly used for copying arrays, merging objects, passing arguments, and creating updated versions of existing data without modifying originals. Example: const arr1 = [1,2]; const arr2 = [...arr1, 3];

Q26

What is the rest parameter?

The rest parameter collects multiple function arguments into a single array using .... It helps handle variable numbers of arguments inside functions and makes function definitions cleaner compared to using the older arguments object. Example: function sum(...numbers) { return numbers.length; }

Q27

What is object destructuring?

Object destructuring allows extracting object properties into variables quickly. It improves readability and avoids repeatedly accessing object properties. This feature is commonly used in React, API handling, and modern JavaScript applications. Example: const user = {name: "Sam", age: 22}; const {name, age} = user;

Q28

How do you clone an object in JavaScript?

Objects can be cloned using the spread operator, Object.assign(), or deep-copy techniques like structuredClone(). Cloning prevents accidental modification of the original object while working with copied data. Example: const user = {name: "John"}; const copy = {...user};

Q29

What is optional chaining (?.) ?

Optional chaining safely accesses nested object properties without causing errors if a property does not exist. Instead of throwing an error, it returns undefined. It makes handling API responses and optional data structures much easier. Example: console.log(user?.address?.city);

Q30

What is the difference between shallow copy and deep copy?

A shallow copy duplicates only the top-level properties, while nested objects still share references. A deep copy duplicates everything completely, including nested objects. Deep copies prevent unexpected changes when working with complex object structures. Example: const copy = JSON.parse(JSON.stringify(obj));

DOM & Events

Q31

What is the DOM?

The DOM, or Document Object Model, represents an HTML document as a tree structure. JavaScript uses the DOM to access, modify, create, or delete elements dynamically, making webpages interactive without reloading the entire page. Example: document.body.style.background = "yellow";

Q32

How do you select elements in JavaScript?

JavaScript provides methods like getElementById(), querySelector(), and querySelectorAll() to select HTML elements. These methods help developers manipulate content, styles, and events dynamically based on user interaction. Example: const heading = document.querySelector("h1");

Q33

What is event bubbling?

Event bubbling is the process where an event starts from the target element and moves upward through parent elements. It allows parent elements to react to child events and is commonly used in event delegation techniques. Example: child.addEventListener("click", () => { console.log("Child clicked"); });

Q34

What is event capturing?

Event capturing is the opposite of event bubbling. The event first travels from the top parent element down to the target element. Capturing is less commonly used but helps control event execution order when needed. Example: parent.addEventListener("click", handler, true);

Q35

What is event delegation?

Event delegation is a technique where a parent element handles events for its child elements using bubbling. Instead of adding listeners to multiple elements, a single listener improves performance and reduces memory usage. Example: document.querySelector("ul").addEventListener("click", e => { console.log(e.target); });

Q36

What is the difference between innerHTML, innerText, and textContent?

innerHTML returns HTML content including tags. innerText returns visible text only. textContent returns all text content, including hidden text. Developers choose based on whether they need HTML rendering or plain text manipulation. Example: element.innerHTML = "<b>Hello</b>";

Q37

How do you create elements dynamically in JavaScript?

JavaScript can create HTML elements dynamically using createElement(). After creating the element, developers can add content, styles, or attributes before appending it to the webpage using methods like appendChild(). Example: const div = document.createElement("div"); document.body.appendChild(div);

Q38

What is addEventListener()?

addEventListener() attaches an event handler to an HTML element without overwriting existing events. It supports multiple event listeners and allows better control over event handling compared to inline event attributes. Example: button.addEventListener("click", () => { alert("Clicked"); });

Q39

What is the difference between preventDefault() and stopPropagation()?

preventDefault() stops the browser's default behavior, like form submission. stopPropagation() stops the event from moving to parent elements during bubbling or capturing. Both are important for controlling event behavior in applications. Example: event.preventDefault(); event.stopPropagation();

Q40

What is form validation in JavaScript?

Form validation checks whether user input meets required conditions before submission. It improves data accuracy and user experience by preventing invalid information like empty fields, incorrect email formats, or weak passwords. Example: if(input.value === "") { alert("Field required"); }

Async JavaScript

Q41

What is asynchronous JavaScript?

Asynchronous JavaScript allows tasks to run without blocking the execution of other code. It helps handle operations like API requests, file loading, and timers efficiently, improving performance and user experience in web applications. Example: setTimeout(() => { console.log("Done"); }, 1000);

Q42

What is the difference between synchronous and asynchronous code?

Synchronous code executes line by line, waiting for each task to finish before continuing. Asynchronous code allows other tasks to run while waiting for operations like API calls or timers, improving application responsiveness. Example: console.log("Start"); setTimeout(() => console.log("End"), 1000);

Q43

What is a Promise?

A Promise is an object representing the eventual completion or failure of an asynchronous operation. It has three states: pending, fulfilled, and rejected. Promises simplify asynchronous programming and avoid deeply nested callback structures. Example: const promise = new Promise((resolve) => { resolve("Success"); });

Q44

What are async and await?

async and await simplify working with promises by making asynchronous code look synchronous. An async function always returns a promise, and await pauses execution until the promise resolves or rejects. Example: async function getData() { let data = await fetch(url); }

Q45

What is the difference between callbacks, promises, and async/await?

Callbacks execute functions after tasks finish but can become difficult to manage. Promises improve readability and chaining. async/await provides the cleanest syntax by making asynchronous code easier to read, write, and debug. Example: fetch(url) .then(res => res.json()) .catch(err => console.log(err));

Q46

What is the event loop in JavaScript?

The event loop is a mechanism that manages asynchronous operations in JavaScript. It continuously checks the call stack and callback queue, executing queued tasks when the stack becomes empty. This enables non-blocking behavior in single-threaded JavaScript. Example: console.log("A"); setTimeout(() => console.log("B"), 0); console.log("C");

Q47

What is setTimeout()?

setTimeout() is a JavaScript function that executes code after a specified delay in milliseconds. It is commonly used for timers, animations, delayed actions, and asynchronous behavior inside web applications. Example: setTimeout(() => { console.log("Hello after 2 seconds"); }, 2000);

Q48

What is API fetching in JavaScript?

API fetching means requesting data from a server using JavaScript. Developers commonly use the fetch() method to retrieve JSON data asynchronously and display dynamic content inside applications without refreshing the webpage. Example: fetch("https://api.example.com/data") .then(res => res.json());

Q49

What is JSON?

JSON, or JavaScript Object Notation, is a lightweight format used for storing and exchanging data between systems. It is easy for humans to read and machines to parse, making it widely used in APIs and web applications. Example: const user = '{"name":"John"}';

Q50

What is the difference between localStorage and sessionStorage?

localStorage stores data permanently until manually removed, even after closing the browser. sessionStorage stores data only for the current browser session and clears automatically when the tab or browser closes. Example: localStorage.setItem("name", "Sam"); sessionStorage.setItem("theme", "dark");