savanka

50 JavaScript Interview Questions and Answers

JavaScript is one of the most widely used programming languages in web development. Whether you’re preparing for your first frontend interview or applying for a senior developer role, interviewers often test your understanding of JavaScript fundamentals, ES6 features, asynchronous programming, the DOM, and advanced concepts.

In this guide, you’ll find 50 carefully selected JavaScript interview questions and answers, ranging from beginner to advanced level, to help you prepare with confidence.


Basic JavaScript Interview Questions

1. What is JavaScript?

JavaScript is a lightweight, high-level, interpreted programming language used to build interactive web applications. It runs in browsers and can also be executed on servers using Node.js.


2. What are the data types in JavaScript?

JavaScript has two categories of data types:

Primitive Types

  • String
  • Number
  • Boolean
  • Undefined
  • Null
  • Symbol
  • BigInt

Non-Primitive Types

  • Object
  • Array
  • Function

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

varletconst
Function scopedBlock scopedBlock scoped
Can be redeclaredCannot be redeclaredCannot be redeclared
Can be updatedCan be updatedCannot be updated

Example

var a = 10;
let b = 20;
const c = 30;

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

==

Compares values after type conversion.

5 == "5" // true

===

Compares both value and type.

5 === "5" // false

Always prefer ===.


5. What is Hoisting?

Hoisting is JavaScript’s behavior of moving variable and function declarations to the top of their scope before execution.

Example

console.log(a);

var a = 10;

Output

undefined

6. What is a Closure?

A closure allows a function to access variables from its outer scope even after the outer function has finished executing.

Example

function outer(){

let count = 0;

return function(){

count++;

console.log(count);

}

}

const counter = outer();

counter();

counter();

Output

1
2

7. What is Scope?

Scope determines where variables can be accessed.

Types include:

  • Global Scope
  • Function Scope
  • Block Scope

8. What is an Arrow Function?

Arrow functions provide shorter syntax.

const add = (a,b) => a+b;

9. What is the difference between null and undefined?

nullundefined
Intentional empty valueVariable not assigned
Object typeUndefined type

10. What is NaN?

NaN stands for Not a Number.

Example

Number("Hello")

Output

NaN

ES6 Interview Questions

11. What are Template Literals?

Template literals allow string interpolation.

let name="John";

console.log(`Hello ${name}`);

12. What are Default Parameters?

function greet(name="Guest"){

console.log(name);

}

13. What is Destructuring?

const person={

name:"John",

age:25

};

const {name,age}=person;

14. What is the Spread Operator?

const a=[1,2];

const b=[...a,3];

Output

[1,2,3]

15. What is the Rest Operator?

function sum(...numbers){

return numbers.reduce((a,b)=>a+b);

}

16. What are Modules?

Modules allow code to be split into reusable files.

export default App;
import App from './App';

17. What is Optional Chaining?

user?.address?.city

It prevents runtime errors if a property is undefined.


18. What is Nullish Coalescing?

const value = name ?? "Guest";

Returns the right value only if the left side is null or undefined.


19. What are Promises?

Promises handle asynchronous operations.

States:

  • Pending
  • Fulfilled
  • Rejected

20. What is async/await?

async function getUsers(){

const response=await fetch(url);

}

It makes asynchronous code easier to read.

21. What is the Event Loop?

The Event Loop is a mechanism that allows JavaScript to perform non-blocking operations even though it is single-threaded.

It continuously checks the Call Stack and Callback Queue. If the Call Stack is empty, it moves queued callbacks into the Call Stack for execution.


22. What is a Callback Function?

A callback is a function passed as an argument to another function and executed later.

Example

function greet(name, callback) {
    console.log("Hello " + name);
    callback();
}

function done() {
    console.log("Completed");
}

greet("John", done);

23. What is Callback Hell?

Callback Hell occurs when multiple nested callbacks make the code difficult to read and maintain.

Example

login(function () {
    getUser(function () {
        getOrders(function () {
            getPayment(function () {

            });
        });
    });
});

Promises and async/await solve this problem.


24. What is Event Delegation?

Event Delegation is a technique where a parent element handles events for its child elements using event bubbling.

Example

document.getElementById("list").addEventListener("click", function(e) {

    if (e.target.tagName === "LI") {
        console.log(e.target.textContent);
    }

});

It improves performance by reducing the number of event listeners.


25. What is the DOM?

DOM (Document Object Model) is a tree-like representation of an HTML document.

JavaScript can:

  • Create elements
  • Remove elements
  • Modify HTML
  • Change CSS
  • Handle events

26. Difference Between innerHTML and innerText?

innerHTMLinnerText
Returns HTMLReturns only visible text
Can insert HTML tagsCannot insert HTML
FasterSlightly slower

Example

element.innerHTML = "<b>Hello</b>";

27. Difference Between localStorage and sessionStorage?

localStoragesessionStorage
No expirationCleared when browser closes
Shared across tabsOnly current tab
Stores data permanentlyTemporary storage

28. What is JSON?

JSON stands for JavaScript Object Notation.

Example

{
    "name":"John",
    "age":25
}

Convert Object to JSON

JSON.stringify(user);

Convert JSON to Object

JSON.parse(jsonData);

29. What is Fetch API?

Fetch API is used to make HTTP requests.

Example

fetch("/users")
.then(response => response.json())
.then(data => console.log(data));

30. Difference Between fetch() and XMLHttpRequest?

Fetch APIXMLHttpRequest
Promise-basedCallback-based
Cleaner syntaxMore verbose
ModernOlder API
Better readabilityLess readable

Fetch is recommended for modern applications.


31. What is Event Bubbling?

In Event Bubbling, an event propagates from the target element up to its parent elements.

Example

<div id="parent">
    <button id="child">Click</button>
</div>

Clicking the button triggers:

  1. Button
  2. Parent
  3. Document

32. What is Event Capturing?

Event Capturing is the opposite of bubbling.

The event travels:

Document → Parent → Child

Enable capturing

element.addEventListener("click", handler, true);

33. What is stopPropagation()?

It prevents event bubbling.

Example

button.addEventListener("click", function(event){

    event.stopPropagation();

});

34. What is preventDefault()?

It prevents the browser’s default action.

Example

form.addEventListener("submit", function(e){

    e.preventDefault();

});

35. What is the this Keyword?

this refers to the object calling the function.

Example

const user = {

    name: "John",

    greet() {
        console.log(this.name);
    }

};

Output

John

36. What is call()?

call() invokes a function with a specified this value.

Example

function greet(){

    console.log(this.name);

}

const user = {

    name:"John"

};

greet.call(user);

37. What is apply()?

apply() works like call() but accepts arguments as an array.

Example

function sum(a,b){

console.log(a+b);

}

sum.apply(null,[5,10]);

38. What is bind()?

bind() returns a new function with a fixed this value.

Example

const person = {

name:"John"

};

function greet(){

console.log(this.name);

}

const newFunc = greet.bind(person);

newFunc();

39. Difference Between call(), apply(), and bind()

call()apply()bind()
Executes immediatelyExecutes immediatelyReturns new function
Arguments individuallyArguments as arrayArguments later

40. What is a Prototype?

Every JavaScript object has a prototype from which it inherits properties and methods.

Example

function Person(name){

this.name=name;

}

Person.prototype.sayHello=function(){

console.log("Hello");

};

This enables inheritance in JavaScript.

41. What is the Difference Between map(), filter(), and reduce()?

These are the three most commonly used array methods.

map()

Returns a new array after transforming every element.

const numbers = [1, 2, 3];

const doubled = numbers.map(num => num * 2);

console.log(doubled);

Output

[2, 4, 6]

filter()

Returns elements that satisfy a condition.

const numbers = [1,2,3,4,5];

const even = numbers.filter(num => num % 2 === 0);

console.log(even);

Output

[2,4]

reduce()

Reduces an array into a single value.

const numbers = [1,2,3,4];

const sum = numbers.reduce((total, num) => total + num, 0);

console.log(sum);

Output

10

42. What is a Shallow Copy and Deep Copy?

Shallow Copy

Copies only the first level of an object.

const user = {
    name: "John"
};

const copy = { ...user };

Nested objects still share the same reference.


Deep Copy

Creates an entirely independent copy.

const copy = structuredClone(user);

Deep copies prevent accidental modification of nested objects.


43. What is Garbage Collection?

Garbage Collection is JavaScript’s automatic memory management process.

It removes objects from memory that are no longer reachable, preventing memory leaks.

Developers don’t manually free memory in JavaScript.


44. What are Memory Leaks?

A memory leak occurs when memory that is no longer needed is never released.

Common causes include:

  • Unremoved event listeners
  • Global variables
  • Forgotten timers
  • Closures holding unnecessary references
  • Detached DOM elements

Memory leaks can slow down applications over time.


45. What is Debouncing?

Debouncing limits how often a function executes by waiting until the user stops performing an action.

Common use cases:

  • Search boxes
  • Auto-save
  • Window resize
  • API calls

Example

function debounce(fn, delay) {

    let timer;

    return function () {

        clearTimeout(timer);

        timer = setTimeout(() => {
            fn();
        }, delay);

    };

}

46. What is Throttling?

Throttling ensures a function executes at most once during a specified time interval.

Common use cases:

  • Scroll events
  • Mouse movement
  • Window resizing
  • Infinite scrolling

Unlike debouncing, throttling executes continuously but at a controlled rate.


47. Difference Between Debouncing and Throttling

DebouncingThrottling
Waits until the action stopsExecutes at regular intervals
Best for search inputBest for scrolling
Fewer executionsRegular executions
Reduces unnecessary API callsImproves scrolling performance

48. What are Generators in JavaScript?

Generators are special functions that can pause and resume execution.

They use the function* syntax.

Example

function* numbers() {

    yield 1;
    yield 2;
    yield 3;

}

const generator = numbers();

console.log(generator.next().value);
console.log(generator.next().value);

Output

1
2

Generators are useful for lazy evaluation and custom iterators.


49. What are Iterators?

An iterator is an object that allows sequential access to values.

Example

const arr = [10, 20, 30];

const iterator = arr[Symbol.iterator]();

console.log(iterator.next());

console.log(iterator.next());

Output

{ value: 10, done: false }

{ value: 20, done: false }

Many JavaScript objects like arrays, strings, maps, and sets are iterable.


50. Why Should You Learn Modern JavaScript?

Modern JavaScript (ES6+) introduces powerful features that make code cleaner, faster, and easier to maintain.

Some of the most important features include:

  • Arrow Functions
  • Template Literals
  • Destructuring
  • Spread and Rest Operators
  • Modules
  • Classes
  • Promises
  • Async/Await
  • Optional Chaining
  • Nullish Coalescing
  • Map, Filter, Reduce
  • Generators
  • Iterators

Mastering these concepts is essential for frameworks like Angular, React, Vue, Next.js, and Node.js.

Explore More

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *