JavaScript Interview Questions and Answers: A Complete Beginner-Friendly Guide

             


If you have ever prepared for a JavaScript interview, you already know one thing: interviewers rarely focus only on coding.

Many times, they want to understand how well you know the fundamentals.

Questions such as:

  • What is JavaScript?
  • What is dynamic typing?
  • What is a prototype chain?
  • What is the difference between call(), apply(), and bind()?
  • What is JSON?
  • What is the difference between slice() and splice()?

These questions appear in interviews for freshers, junior developers, and even experienced engineers.

In this article, we will go through some of the most commonly asked JavaScript interview questions  with practical examples and real-world explanations.

 

What is JavaScript?

Imagine opening an online shopping website.

You click the "Add to Cart" button, products instantly appear in the cart, forms validate while typing, and notifications pop up without reloading the page.

All this interactivity is possible because of JavaScript.

JavaScript is a scripting language used to make web pages interactive and dynamic.

Originally, JavaScript was designed to run inside web browsers. Today, it is used everywhere:

  • Frontend Development
  • Backend Development (Node.js)
  • Mobile Applications
  • Desktop Applications
  • Games
  • Serverless Applications
  • Cloud Services
JavaScript is a scripting language used in client side that allows us (developers) to make web pages interactive.***

 A scripting language is a kind of programming language that is used to automate the execution of operations in a runtime environment.

JavaScript is an object-based scripting language, meaning it uses objects to represent data and functionality,
JavaScript is also cross-platform, which means it can be run on any device that has a web browser,
JavaScript follow synchronous pattern
JavaScript code is a single thread, which means that code can only do one task at a time.
Dynamic Typing ****
JavaScript is dynamically typed, which means: we don’t need to mention the type of a variable.
A variable can hold any type of value, and it can change later.

let x = 10;           // x is a number
x = "Hello";         // now x is a string
x = [1, 2, 3];      // now x is an array
x = { name: "JS" } // now x is an object



Why is JavaScript Called a Scripting Language?

A scripting language automates tasks inside an existing environment.

Instead of creating everything from scratch, scripts work within another system.

For example:

  • Browser + JavaScript
  • Photoshop + Scripts
  • Excel + VBA Scripts

JavaScript runs inside browsers and helps automate user interactions.


Key Features of JavaScript

Dynamic Typing

JavaScript is dynamically typed.

This means you don't need to declare data types explicitly.

Example:

let value = 10;        // Number

value = "Hello";       // String

value = [1, 2, 3];     // Array

value = {name: "JS"};  // Object

The same variable can store different types of values.

This flexibility makes development faster but sometimes introduces unexpected bugs.


Object-Based Language

JavaScript heavily relies on objects.

Almost everything in JavaScript revolves around objects.

Example:

const user = {
    name: "John",
    age: 25
};

Objects help organize data and behavior together.


Cross Platform

JavaScript works on:

  • Windows
  • Linux
  • macOS
  • Android
  • iOS

If a device has a browser, JavaScript can run on it.


Single Threaded

JavaScript can perform only one task at a time.

Think of a single cashier at a grocery store.

Customers stand in a queue.

The cashier serves one customer before moving to the next.

JavaScript works similarly using a single thread.


Synchronous by Nature

JavaScript executes code line by line.

Example:

console.log("First");

console.log("Second");

console.log("Third");

Output:

First
Second
Third

Each statement waits for the previous statement to finish.


What Are the Different Ways to Create Objects in JavaScript?

Objects are one of the most important concepts in JavaScript.

There are multiple ways to create them.


1. Using Object Constructor

var object = new Object();

This creates an empty object.

Although valid, developers usually prefer object literals because they are simpler and cleaner.


2. Using Object.create()

var object = Object.create(null);

The Object.create() method creates a new object using a specified prototype.

This method is useful when working with inheritance and prototype chains.


3. Using Object Literal Syntax

This is the most common approach.

const user = {};

Or:

const user = {
    name: "Tony",
    age: 30
};

Simple, readable, and widely used.


4. Using Function Constructors

Before ES6 classes existed, constructor functions were commonly used.

function Person(name) {
    this.name = name;
    this.age = 21;
}

const person = new Person("John");

The new keyword creates a new object instance.


5. Using ES6 Classes

Modern JavaScript introduced classes.

class Person {
    constructor(name) {
        this.name = name;
    }
}

const person = new Person("John");

Classes make object creation more structured and readable.


What is a Prototype Chain?

One of the most important JavaScript interview topics is the prototype chain.

Real-World Example

Imagine you own a small shop.

If you don't have a product in your shop, you ask your warehouse.

If the warehouse doesn't have it, it asks the main supplier.

This searching process continues until the item is found.

JavaScript follows a similar process.

When an object cannot find a property, it searches its prototype.

If the property isn't there, JavaScript searches the next prototype.

This continues until it reaches null.

This process is called the Prototype Chain.

Example:

const person = {
    name: "John"
};

console.log(person.toString());

Even though toString() isn't inside person, JavaScript finds it through the prototype chain.   



What is the Difference Between Call, Apply, and Bind?

This is one of the most popular JavaScript interview questions.

All three methods help control the value of this.


Understanding the Problem First

Suppose you have a function:

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

Different objects may want to use the same function.

Call, Apply, and Bind help us decide which object should become this.


Call Method

call() executes the function immediately.

Arguments are passed individually.

const employee = {
    name: "Tony"
};

function greet(message) {
    console.log(message + " " + this.name);
}

greet.call(employee, "Hello");

Output:

Hello Tony

Apply Method

apply() is almost identical to call().

The only difference is that arguments are passed as an array.

greet.apply(employee, ["Hello"]);

Output:

Hello Tony

Bind Method

bind() does not execute immediately.

Instead, it returns a new function.

const newFunction = greet.bind(employee);

newFunction("Hello");

Output:

Hello Tony


Quick Comparison Table

Method             Executes Immediately        Arguments
call()Yes                                         One by one
apply()YesArray
bind()NoReturns new function

What is JSON?

JSON stands for JavaScript Object Notation.

It is the most popular format used to exchange data between systems.

Whenever your frontend communicates with a backend API, JSON is usually involved.

Example:

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

Why is JSON So Popular?

Lightweight

JSON contains less unnecessary text compared to XML.

This makes data transfer faster.


Easy to Read

Humans can easily understand JSON structure.


Native JavaScript Support

JavaScript can convert JSON into objects using:

JSON.parse()

And convert objects into JSON using:

JSON.stringify()

Universal Support

Almost every programming language supports JSON.

Examples:

  • Java
  • Python
  • PHP
  • Node.js
  • C#
  • Go

 

What is the Purpose of the Slice() Method?

The slice() method extracts a portion of an array.

Important point:

It does not modify the original array.

Example:

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

let result = numbers.slice(0, 2);

console.log(result);

Output:

[1, 2]

Original array remains unchanged:

[1, 2, 3, 4, 5]

When Should You Use slice()?

Use slice() when:

  • You need a copy of data
  • You don't want to change the original array
  • You need a subset of elements

What is the Purpose of the Splice() Method?

Unlike slice(), splice() modifies the original array.

It can:

  • Add elements
  • Remove elements
  • Replace elements

Removing Elements

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

numbers.splice(1, 2);

Result:

[1, 4, 5]

Adding Elements

numbers.splice(1, 0, "A");

Result:

[1, "A", 4, 5]

Replacing Elements

numbers.splice(1, 1, "B");

Result:

[1, "B", 4, 5]

Difference Between Slice() and Splice()

This question appears in almost every JavaScript interview.

Featureslice()splice()
Original ArrayUnchangedModified
Return ValueNew ArrayRemoved Elements
PurposeExtract DataAdd/Remove/Replace
Side EffectsNoYes

Easy Way to Remember

Think of a cake.

Slice

You cut a piece and take it.

The original cake remains intact.

Splice

You cut the cake, remove pieces, and even add new pieces.

The original cake changes permanently.

That's exactly how these methods behave in JavaScript.


Common Interview Questions Based on Slice and Splice

Does slice() modify the original array?

No.

It returns a new array.


Does splice() modify the original array?

Yes.

It directly changes the original array.


Which method is safer?

Generally, slice() is safer because it doesn't affect the original data.


Final Thoughts

Most JavaScript interviews don't focus only on writing code.

Interviewers often test whether you understand the concepts behind the language.

Topics like:

  • JavaScript fundamentals
  • Dynamic Typing
  • Object Creation
  • Prototype Chain
  • Call, Apply, Bind
  • JSON
  • Slice vs Splice

are frequently asked in interviews because they reveal how deeply you understand JavaScript.

Instead of memorizing definitions, try to understand the reasoning behind each concept. Once you connect these ideas with real-world examples, answering interview questions becomes much easier and more natural.

 

Once you are comfortable with JavaScript basics, interviewers usually move toward deeper concepts. These questions help them understand whether you truly know how JavaScript works behind the scenes or whether you have only memorized syntax.

Let's explore some of the most common advanced JavaScript interview questions .


What is Hoisting in JavaScript?

Hoisting is one of the most famous JavaScript interview topics.

Real-Life Analogy

Imagine you enter a classroom.

Before the teacher starts teaching, the attendance sheet already contains all student names.

Similarly, before JavaScript executes your code, it scans the file and registers variables and functions in memory.

This process is called hoisting.


Variable Hoisting Example

console.log(name);

var name = "Tony";

Output:

undefined

Many beginners expect an error here.

However, JavaScript internally treats the code like this:

var name;

console.log(name);

name = "Tony";

The variable declaration is moved to the top, but the value assignment remains in its original position.


Hoisting with let and const

console.log(age);

let age = 25;

Output:

ReferenceError

Why?

Because let and const are hoisted differently.

They stay inside something called the Temporal Dead Zone (TDZ).

The variable exists in memory, but JavaScript does not allow access before declaration.


Function Hoisting

Function declarations are fully hoisted.

sayHello();

function sayHello() {
    console.log("Hello");
}

Output:

Hello

This works because JavaScript loads the entire function into memory before execution begins.


What is Scope in JavaScript?

Scope determines where variables can be accessed.

Think of scope as room access inside a company.

Some employees can access every room.

Others can only access their department.

Variables behave similarly.


Global Scope

Variables declared outside functions belong to global scope.

let company = "TechCorp";

function showCompany() {
    console.log(company);
}

Every function can access global variables.


Function Scope

Variables declared inside functions remain available only inside that function.

function test() {
    let message = "Hello";
}

console.log(message);

Output:

ReferenceError

The variable lives only inside the function.


Block Scope

Introduced with ES6.

{
    let city = "Delhi";
}

console.log(city);

Output:

ReferenceError

The variable exists only inside that block.


What is a Closure?

Closures are among the most important JavaScript interview questions.

Many developers fear closures because the definition sounds complicated.

In reality, the idea is simple.


Real-Life Example

Imagine you leave your office for the day.

Before leaving, you write some notes and keep them in your backpack.

Even after leaving the office, you still have access to those notes.

Closures work similarly.

A function remembers variables from its outer scope even after the outer function finishes execution.


Example

function outer() {

    let count = 0;

    return function inner() {
        count++;
        console.log(count);
    };
}

const counter = outer();

counter();
counter();
counter();

Output:

1
2
3

Even though outer() has already finished executing, the inner function still remembers count.

That memory is called a closure.


Real-World Uses of Closures

Closures are commonly used in:

  • Data privacy
  • Counters
  • Event handlers
  • Callbacks
  • React Hooks
  • Module patterns

What is a Lexical Environment?

Whenever JavaScript creates a function, it also creates a lexical environment.

This environment stores:

  • Variables
  • Functions
  • References to outer scopes

Simple Example

let company = "Google";

function developer() {

    let name = "John";

    function display() {
        console.log(name);
        console.log(company);
    }

    display();
}

The function display() can access:

  • Its own variables
  • Parent variables
  • Global variables

This behavior is called lexical scoping.


What Are Higher Order Functions?

A higher-order function is a function that:

  • Accepts another function as an argument
  • Returns another function

or both.


Real-Life Example

Think about a manager.

A manager doesn't do every task personally.

Instead, they assign work to other employees.

Higher-order functions work similarly.

They coordinate other functions.


Example

function greet(name) {
    return "Hello " + name;
}

function processUser(callback) {
    console.log(callback("John"));
}

processUser(greet);

Output:

Hello John

The function processUser() accepts another function as an argument.

Therefore it is a higher-order function.


What is the Map() Method?

The map() method creates a new array by transforming every element.


Example

const numbers = [1, 2, 3];

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

console.log(result);

Output:

[2, 4, 6]


Real-Life Example

Imagine a teacher converting student marks into grades.

The number of students remains the same.

Only the values change.

That is exactly how map() works.


What is the Filter() Method?

The filter() method creates a new array containing only matching elements.


Example

const ages = [12, 18, 20, 15, 30];

const adults = ages.filter(age => age >= 18);

console.log(adults);

Output:

[18, 20, 30]

Real-Life Example

Imagine a security guard checking IDs.

Only adults can enter the event.

The guard filters the crowd.

JavaScript's filter() works similarly.


What is the Reduce() Method?

The reduce() method combines multiple values into a single value.


Example

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

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

console.log(total);

Output:

10

Real-Life Example

Think of calculating monthly expenses.

Many transactions exist.

You want one final amount.

Reduce() helps combine everything into a single result.


Difference Between Map, Filter, and Reduce

MethodPurpose
map()Transform values
filter()Select values
reduce()Combine values

What is Function Borrowing?

Function borrowing allows one object to use another object's method.

This is usually achieved using call(), apply(), or bind().


Example

const person1 = {
    name: "Tony",
    display() {
        console.log(this.name);
    }
};

const person2 = {
    name: "Steve"
};

person1.display.call(person2);

Output:

Steve

The method belongs to person1 but is borrowed by person2.


What is Execution Context in JavaScript?

If you have ever wondered how JavaScript knows which code to run first, where variables are stored, or how functions get access to data, then you need to understand Execution Context.

This is one of the most frequently asked JavaScript interview topics because it explains what happens behind the scenes whenever JavaScript executes code.

Real-World Analogy

Imagine a restaurant kitchen.

Before cooking begins, the chef prepares the workspace:

  • Ingredients are collected.

  • Tools are arranged.

  • Orders are reviewed.

Only after preparation does the actual cooking begin.

JavaScript behaves similarly.

Before executing code, it creates an environment to manage variables, functions, and execution flow.

This environment is called an Execution Context.


Types of Execution Context

JavaScript mainly creates two types of execution contexts.

Global Execution Context (GEC)

Whenever a JavaScript file starts running, the Global Execution Context is created automatically.

Example:

let company = "Tech World";

function greet() {
    console.log("Welcome");
}

Before executing this code, JavaScript creates the Global Execution Context.

There is always one Global Execution Context.


Function Execution Context (FEC)

Whenever a function is called, JavaScript creates a new execution context for that function.

Example:

function greet() {
    let name = "John";
    console.log(name);
}

greet();

When greet() executes, JavaScript creates a separate Function Execution Context.

Every function call gets its own execution context.


Phases of Execution Context

JavaScript execution happens in two phases.

Memory Creation Phase

During this phase:

  • Variables receive initial values.

  • Function declarations are stored in memory.

Example:

var name = "Tony";

function greet() {
    console.log("Hello");
}

Internally JavaScript stores:

name = undefined

greet = function definition

No code executes yet.

JavaScript is simply preparing memory.


Execution Phase

In this phase:

  • Code runs line by line.

  • Variables receive actual values.

  • Functions execute.

Example:

var name = "Tony";

Now:

name = "Tony"

The actual value gets assigned.


What is the Call Stack?

The Call Stack is another favorite interview topic.

Real-World Example

Imagine a stack of plates.

You always place a new plate on top.

When removing plates, you remove the top plate first.

This follows the Last In First Out (LIFO) principle.

JavaScript uses the same approach.

Whenever a function is called, it gets pushed onto the Call Stack.

Once the function finishes, it gets removed.


Example

function first() {
    second();
}

function second() {
    third();
}

function third() {
    console.log("Hello");
}

first();

Execution order:

Call Stack

first()
second()
third()

After completion:

third() removed
second() removed
first() removed

The stack becomes empty.


Why is the Call Stack Important?

The Call Stack helps JavaScript:

  • Track active functions

  • Manage execution order

  • Handle function calls efficiently

Without the Call Stack, JavaScript would not know which function should execute next.


What is Synchronous Programming?

By default, JavaScript follows synchronous execution.

This means tasks execute one after another.

Example:

console.log("Task 1");

console.log("Task 2");

console.log("Task 3");

Output:

Task 1
Task 2
Task 3

JavaScript waits for each task to finish before moving to the next.


Problem with Synchronous Programming

Imagine downloading a huge file.

If JavaScript waits for the download to complete before doing anything else, the application would freeze.

To solve this issue, JavaScript introduced asynchronous programming.


What is Asynchronous Programming?

Asynchronous programming allows long-running tasks to execute in the background without blocking other operations.

Example:

console.log("Start");

setTimeout(() => {
    console.log("Downloaded");
}, 3000);

console.log("End");

Output:

Start
End
Downloaded

Even though the timeout appears earlier in the code, JavaScript doesn't wait.

This behavior is possible because of the Event Loop.


What is the Event Loop?

The Event Loop is one of the most important JavaScript concepts.

Almost every JavaScript interview eventually reaches this topic.

Real-World Analogy

Imagine a restaurant manager.

The manager constantly checks:

  • Is the chef busy?

  • Is there a new order waiting?

  • Is any task completed?

The manager keeps monitoring everything.

The Event Loop behaves similarly.

It continuously checks whether the Call Stack is empty.

If the stack is empty, it moves waiting tasks into the stack for execution.


Components Involved in Event Loop

To understand the Event Loop, you need to know four important components.

Call Stack

Handles execution.

Web APIs

Provided by browsers.

Examples:

  • setTimeout

  • DOM Events

  • Fetch API

  • Geolocation API

Callback Queue

Stores completed callback functions.

Event Loop

Moves callbacks from the queue into the Call Stack.


Event Loop Flow Example

console.log("Start");

setTimeout(() => {
    console.log("Timer Done");
}, 2000);

console.log("End");

Step 1:

Start

Printed immediately.


Step 2:

setTimeout moves to Web APIs.

Timer starts.


Step 3:

End

Printed immediately.


Step 4:

Timer completes.

Callback enters Callback Queue.


Step 5:

Event Loop notices the Call Stack is empty.

Moves callback into stack.

Output:

Timer Done

What is Callback Queue?

The Callback Queue stores completed asynchronous callbacks waiting for execution.

Example:

setTimeout(() => {
    console.log("Executed");
}, 1000);

After one second:

Callback Queue

[ callback ]

The Event Loop eventually moves this callback to the Call Stack.


What is the Microtask Queue?

This topic is commonly asked in React and Node.js interviews.

Microtasks have higher priority than the Callback Queue.


Example

console.log("Start");

Promise.resolve().then(() => {
    console.log("Promise");
});

setTimeout(() => {
    console.log("Timeout");
}, 0);

console.log("End");

Output:

Start
End
Promise
Timeout

Many beginners expect Timeout before Promise.

However, Promise callbacks enter the Microtask Queue.

Microtasks execute before normal callbacks.


Priority Order

Call Stack

↓

Microtask Queue

↓

Callback Queue

Microtasks always get priority.


What is Callback Hell?

Before Promises existed, developers relied heavily on callbacks.

Multiple nested callbacks created difficult-to-read code.

Example:

getUser(function(user) {

    getOrders(user.id, function(orders) {

        getPayment(orders.id, function(payment) {

            console.log(payment);

        });

    });

});

This structure keeps moving to the right side.

Developers often call it:

Pyramid of Doom

or

Callback Hell

Problems with Callback Hell

  • Hard to read

  • Difficult to debug

  • Difficult to maintain

  • Error handling becomes messy

To solve these problems, JavaScript introduced Promises.


What is a Promise?

A Promise represents the future result of an asynchronous operation.

Think of ordering food online.

You place an order now.

The result arrives later.

A Promise works similarly.


Promise States

A Promise can exist in three states.

Pending

Operation still running.

Fulfilled

Operation completed successfully.

Rejected

Operation failed.


Promise Example

const promise = new Promise((resolve, reject) => {

    let success = true;

    if(success) {
        resolve("Order Delivered");
    } else {
        reject("Order Failed");
    }

});

Consuming Promises

promise
.then(result => {
    console.log(result);
})
.catch(error => {
    console.log(error);
});

What is Promise Chaining?

Instead of nesting callbacks, Promises allow chaining.

Example:

fetchUser()
.then(user => getOrders(user.id))
.then(order => getPayment(order.id))
.then(payment => console.log(payment))
.catch(error => console.log(error));

This approach is much cleaner.


What is Async/Await?

Async/Await is modern syntax built on top of Promises.

It makes asynchronous code look synchronous and easier to understand.


Example

async function fetchData() {

    const response = await fetch(url);

    const data = await response.json();

    console.log(data);

}

Why Developers Love Async/Await

Benefits:

  • Cleaner syntax

  • Easier debugging

  • Better readability

  • Less nesting

  • Easier error handling


Error Handling with Async/Await

Use try/catch blocks.

Example:

async function getData() {

    try {

        const response = await fetch(url);

        const data = await response.json();

        console.log(data);

    } catch(error) {

        console.log(error);

    }
}

This is currently the preferred approach in modern JavaScript applications.


Most Asked Interview Question

What Will Be the Output?

console.log("A");

setTimeout(() => {
    console.log("B");
}, 0);

Promise.resolve().then(() => {
    console.log("C");
});

console.log("D");

Answer

Output:

A
D
C
B

Explanation

  1. A executes.

  2. setTimeout enters Web APIs.

  3. D executes.

  4. Promise enters Microtask Queue.

  5. Microtask Queue executes first.

  6. Timeout executes last.

This single question tests:

  • Event Loop

  • Call Stack

  • Microtask Queue

  • Callback Queue

  • Promise Priority

which is why interviewers love asking it.



Understanding var, let, and const

If there is one JavaScript interview question that almost every developer faces, it is:

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

Many beginners think these three keywords do the same thing because all of them are used to create variables.

However, there are important differences that interviewers expect you to understand.


The Story Behind var

Before ES6 (ECMAScript 2015), JavaScript developers only had one way to declare variables:

var name = "Tony";

For many years, developers used var everywhere.

Unfortunately, var introduced several confusing behaviors that caused bugs in large applications.

To solve these issues, JavaScript introduced:

  • let

  • const


What is var?

var is the traditional way of declaring variables.

Example:

var company = "Google";

Function Scope

Variables declared using var are function-scoped.

Example:

function test() {

    var message = "Hello";

    console.log(message);
}

test();

Output:

Hello

However:

function test() {

    var message = "Hello";
}

console.log(message);

Output:

ReferenceError

The variable only exists inside the function.


Problem with var

Consider:

if(true) {

    var city = "Delhi";

}

console.log(city);

Output:

Delhi

Even though city was declared inside a block, it becomes accessible outside.

This behavior often creates bugs.


What is let?

The let keyword was introduced to solve problems created by var.

Example:

let age = 25;

Block Scope

Unlike var, let respects block boundaries.

Example:

if(true) {

    let city = "Delhi";

}

console.log(city);

Output:

ReferenceError

The variable remains confined to its block.

This makes code safer and easier to maintain.


What is const?

The const keyword creates variables whose references cannot be reassigned.

Example:

const PI = 3.14;

Reassignment Not Allowed

const PI = 3.14;

PI = 10;

Output:

TypeError

JavaScript prevents reassignment.


Important Interview Trick

Many candidates think objects declared using const cannot change.

That is incorrect.

Example:

const user = {
    name: "Tony"
};

user.name = "Steve";

This works successfully.

Why?

Because the object reference remains unchanged.

Only a property inside the object changes.


Comparison Table: var vs let vs const

Featurevarletconst
ScopeFunctionBlockBlock
HoistedYesYesYes
TDZNoYesYes
ReassignYesYesNo
RedeclareYesNoNo

What is the Temporal Dead Zone (TDZ)?

The Temporal Dead Zone is one of the most commonly asked JavaScript interview concepts.

Simple Explanation

The TDZ is the period between:

  • Variable creation

  • Variable declaration

During this time, accessing the variable causes an error.


Example

console.log(age);

let age = 25;

Output:

ReferenceError

Although JavaScript already knows about the variable, it refuses access until the declaration line executes.


What is the this Keyword?

Another favorite interview topic is the this keyword.

Many developers struggle with it because its value changes depending on how a function is called.


Real-Life Analogy

Imagine someone says:

I am a developer.

The meaning of "I" depends on who is speaking.

Similarly, this refers to the object currently calling the function.


Example

const person = {

    name: "Tony",

    greet() {

        console.log(this.name);

    }

};

person.greet();

Output:

Tony

Here:

this === person

Global this

In browsers:

console.log(this);

Output:

window

Arrow Functions in JavaScript

Arrow functions were introduced in ES6.

They provide shorter syntax and different behavior for this.


Traditional Function

function add(a, b) {
    return a + b;
}

Arrow Function

const add = (a, b) => {
    return a + b;
};

Or:

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

Why Arrow Functions Are Popular

Benefits:

  • Shorter syntax

  • Cleaner code

  • Better readability

  • Commonly used in React


Arrow Functions and this

One major difference:

Arrow functions do not create their own this.

Instead, they inherit it from the surrounding scope.

Example:

const user = {

    name: "Tony",

    greet: () => {

        console.log(this.name);

    }

};

user.greet();

Output:

undefined

This question appears frequently in interviews.


What is the Spread Operator?

The spread operator uses three dots:

...

It expands elements from arrays or objects.


Array Example

const numbers = [1, 2, 3];

const newNumbers = [...numbers, 4, 5];

Result:

[1,2,3,4,5]

Object Example

const user = {
    name: "Tony"
};

const updatedUser = {
    ...user,
    age: 25
};

Result:

{
 name: "Tony",
 age: 25
}

What is the Rest Operator?

The rest operator also uses:

...

But it performs the opposite task.

Instead of expanding values, it collects values.


Example

function total(...numbers) {

    console.log(numbers);

}

total(1,2,3,4);

Output:

[1,2,3,4]

Difference Between Spread and Rest

SpreadRest
Expands valuesCollects values
Used while copyingUsed while receiving
Converts array into valuesConverts values into array

What is Destructuring?

Destructuring allows extracting values from arrays and objects easily.


Array Destructuring

const colors = ["Red", "Blue"];

const [first, second] = colors;

Result:

first = "Red"
second = "Blue"

Object Destructuring

const user = {

    name: "Tony",

    age: 25

};

const {name, age} = user;

Result:

name = "Tony"
age = 25

Why Developers Love Destructuring

Benefits:

  • Cleaner code

  • Less repetition

  • Easier readability

  • Commonly used in React and Node.js


What is Currying?

Currying transforms a function with multiple arguments into a sequence of functions with one argument.


Example

Without currying:

function multiply(a,b) {

    return a*b;

}

With currying:

function multiply(a) {

    return function(b) {

        return a*b;

    }

}

Usage:

multiply(5)(10);

Output:

50

Real-Life Example

Imagine ordering pizza.

Step 1:

Choose size.

Step 2:

Choose toppings.

Step 3:

Choose delivery.

Instead of providing everything at once, you provide information gradually.

This is similar to currying.


What is Debouncing?

Debouncing limits how often a function executes.


Real-Life Example

Imagine searching on Google.

If JavaScript sends an API request for every key press:

H
He
Hel
Hell
Hello

Five API calls would occur.

This wastes resources.

Debouncing waits until the user stops typing.

Then only one request is sent.


Common Uses

  • Search bars

  • Auto-complete

  • Input validation


What is Throttling?

Throttling ensures a function executes at a fixed interval.


Real-Life Example

Imagine a security guard allowing only one person every five seconds.

Even if hundreds arrive, entry happens at controlled intervals.

That is throttling.


Common Uses

  • Scroll events

  • Resize events

  • Mouse movements

  • Performance optimization


Difference Between Debouncing and Throttling

DebouncingThrottling
Waits for inactivityExecutes periodically
Ideal for search inputsIdeal for scrolling
Reduces API callsControls execution frequency

What is Local Storage?

Local Storage allows data storage inside the browser.

Data remains available even after closing the browser.

Example:

localStorage.setItem("user","Tony");

Retrieve:

localStorage.getItem("user");

What is Session Storage?

Session Storage is similar to Local Storage.

The difference:

Data disappears when the browser tab closes.


Local Storage vs Session Storage

FeatureLocal StorageSession Storage
PersistencePermanentUntil tab closes
CapacityLargerSmaller
Browser RestartData remainsData removed

What is Event Delegation?

Event Delegation is an optimization technique.

Instead of attaching event listeners to multiple child elements, we attach one listener to the parent.


Example

Instead of:

button1.addEventListener()
button2.addEventListener()
button3.addEventListener()

Attach one listener to the parent container.

This improves performance.


Most Common JavaScript Interview Question

Difference Between == and ===

Double Equals (==)

Performs type conversion.

5 == "5"

Output:

true

Triple Equals (===)

Checks both value and type.

5 === "5"

Output:

false


Advanced JavaScript Interview Questions and Answers

By now, we have covered many of the JavaScript concepts that interviewers commonly ask.

However, when you apply for mid-level, senior-level, React, Node.js, or Full Stack Developer

positions, the discussion often moves beyond basics.

Interviewers start asking questions such as:

  • What is the difference between shallow copy and deep copy?
  • How does JavaScript manage memory?
  • What is garbage collection?
  • What is memoization?
  • What are polyfills?
  • What is the difference between Object.freeze() and Object.seal()?

These questions help interviewers understand whether you know how JavaScript

behaves internally.

Let's explore these topics in a practical and beginner-friendly way.




What is a Shallow Copy in JavaScript?

Imagine your friend gives you a photocopy of a house key.

The copy looks different physically, but both keys open the same house.

A shallow copy behaves similarly.

The top-level object gets copied, but nested objects still reference the same memory location.

Example

const originalUser = {
    name: "Tony",
    address: {
        city: "Delhi"
    }
};

const copiedUser = { ...originalUser };

copiedUser.address.city = "Mumbai";

console.log(originalUser.address.city);

Output:

Mumbai

Many beginners expect the original object to remain unchanged.

However, the nested object is still shared.

This is called a shallow copy.



What is a Deep Copy?

A deep copy creates completely independent copies of all nested objects.

Think of building an entirely new house rather than making a duplicate key.

Changes in the copied object do not affect the original object.

Example

const originalUser = {
    name: "Tony",
    address: {
        city: "Delhi"
    }
};

const copiedUser = structuredClone(originalUser);

copiedUser.address.city = "Mumbai";

console.log(originalUser.address.city);

Output:

Delhi

The original object remains untouched.


Interview Question

Which method is safer?

Generally, deep copy is safer when dealing with nested objects because

it prevents accidental modification of the original data.


What is Object.freeze()?

Sometimes developers want to protect objects from modifications.

JavaScript provides Object.freeze() for this purpose.

Example

const user = {
    name: "Tony"
};

Object.freeze(user);

user.name = "Steve";

console.log(user.name);

Output:

Tony

The update fails silently.

The object becomes read-only.


Real-Life Example

Imagine a government-issued birth certificate.

Once issued, nobody should be able to change its contents.

Object.freeze() works similarly.


What is Object.seal()?

Object.seal() is slightly less restrictive than Object.freeze().

Example

const user = {
    name: "Tony"
};

Object.seal(user);

user.name = "Steve";

console.log(user.name);

Output:

Steve

Existing properties can still change.

However:

user.age = 25;

will not work.

New properties cannot be added.


Difference Between Object.freeze() and Object.seal()

FeatureObject.freeze()Object.seal()
Modify Existing PropertiesNoYes
Add New PropertiesNoNo
Delete PropertiesNoNo

What is Memoization?

Memoization is a performance optimization technique.

It helps avoid repeating expensive calculations.


Real-Life Example

Imagine you run a small grocery store.

A customer asks:

What is the price of milk?

You check your notebook.

Ten minutes later, another customer asks the same question.

Instead of searching again, you immediately provide the answer because you already know it.

Memoization works exactly like that.

It remembers previous results.


Example

function memoizedSquare() {

    const cache = {};

    return function(number) {

        if(cache[number]) {
            return cache[number];
        }

        const result = number * number;

        cache[number] = result;

        return result;
    };
}

const square = memoizedSquare();

console.log(square(5));
console.log(square(5));

The second call uses the cached result.

No additional calculation occurs.


Why Companies Love Memoization

Memoization helps:

  • Improve performance
  • Reduce API requests
  • Reduce calculations
  • Speed up applications

It is commonly used in:

  • React applications
  • Data processing
  • Search systems
  • E-commerce websites

What is Garbage Collection?

Memory management is another popular interview topic.

Many languages require developers to manually release memory.

JavaScript does this automatically.


Real-Life Example

Imagine an office cleaner.

Employees use papers throughout the day.

At night, the cleaner removes unnecessary papers from desks.

This creates more space.

Garbage Collection behaves similarly.

It removes unused objects from memory.


Example

let user = {
    name: "Tony"
};

user = null;

Now the original object is no longer reachable.

JavaScript eventually removes it from memory.


Why Garbage Collection Matters

Without garbage collection:

  • Memory would continuously grow.
  • Applications would become slow.
  • Browsers could crash.

What is a Memory Leak?

A memory leak occurs when memory is no longer needed but still remains allocated.


Real-Life Example

Imagine renting storage units.

You stop using them but continue paying rent.

Over time, expenses grow unnecessarily.

A memory leak behaves similarly.

Unused memory continues occupying space.


Common Causes of Memory Leaks

Unused Event Listeners

button.addEventListener("click", handler);

If never removed:

button.removeEventListener("click", handler);

memory may remain occupied.

Global Variables

name = "Tony";

Accidental global variables may remain in memory longer than expected.


Timers

setInterval(() => {
    console.log("Running");
}, 1000);

If never cleared:

clearInterval(intervalId);

memory usage may continue increasing.


What is a Polyfill?

Polyfills are another common interview topic.

Real-Life Example

Imagine visiting an old apartment.

The building doesn't have an elevator.

The owner installs an elevator later.

Now old and new residents enjoy the same functionality.

Polyfills work similarly.

They add modern JavaScript features to older browsers.

Example

Suppose an old browser does not support:

Array.prototype.includes()

A developer can create a custom implementation.

if(!Array.prototype.includes) {

    Array.prototype.includes = function(value) {

        return this.indexOf(value) !== -1;

    };

}

This custom implementation is called a polyfill.



What are JavaScript Modules?

As applications grow, keeping everything inside one file becomes difficult.

Modules help organize code.


Real-Life Example

Imagine a large library.

Books are organized into sections:

  • Science
  • History
  • Mathematics

Without organization, finding books becomes difficult.

Modules provide similar organization for code.


Export Example

export function add(a, b) {
    return a + b;
}

Import Example

import { add } from "./math.js";

Modules improve:

  • Readability
  • Maintainability
  • Scalability

What is the Module Pattern?

Before ES6 modules existed, developers used the Module Pattern.


Example

const Counter = (function() {

    let count = 0;

    return {

        increment() {
            count++;
        },

        getCount() {
            return count;
        }

    };

})();

The variable count remains private.

Only public methods can access it.


Why Was It Popular?

Benefits:

  • Encapsulation
  • Data privacy
  • Cleaner architecture

What is a Set in JavaScript?

A Set stores unique values.

Duplicates are automatically removed.


Example

const numbers = new Set([1,1,2,2,3,3]);

console.log(numbers);

Output:

{1,2,3}

Real-Life Example

Imagine a guest list.

If the same person registers five times, they should appear only once.

A Set works exactly like that.



What is a Map in JavaScript?

Map stores key-value pairs.

Unlike objects, Map allows almost any data type as a key.


Example

const users = new Map();

users.set(1, "Tony");

users.set(2, "Steve");

Retrieve:

users.get(1);

Output:

Tony

Difference Between Object and Map

ObjectMap
String keys mostlyAny data type as key
Older structureModern structure
Limited built-in methodsRich API

What is WeakMap?

WeakMap is similar to Map but has special memory behavior.

Keys must be objects.

When an object becomes unreachable, JavaScript automatically removes it from memory.

This helps avoid memory leaks.


What is WeakSet?

WeakSet behaves similarly to Set.

However:

  • Stores only objects
  • Weakly references objects
  • Helps memory management

Rapid-Fire JavaScript Interview Questions

Is JavaScript compiled or interpreted?

Modern JavaScript engines use Just-In-Time (JIT) compilation.

It is both interpreted and compiled.


Is JavaScript single-threaded?

Yes.

JavaScript uses a single thread for execution.


Can JavaScript perform asynchronous operations?

Yes.

Using:

  • Promises
  • Async/Await
  • Event Loop
  • Web APIs

What is NaN?

NaN means:

Not a Number

Example:

Number("Hello");

Output:

NaN

What is the result of:

typeof null

Output:

object

This is considered a historical JavaScript bug.


Is an empty array truthy?

if([])

Yes.

Arrays are truthy values.


Is an empty object truthy?

if({})

Yes.

Objects are also truthy values.

Post a Comment

0 Comments