Web Development - HTML, CSS & JavaScript
55.7K subscribers
1.87K photos
5 videos
34 files
494 links
Learn to code and become a Web Developer with HTML, CSS, JavaScript , Reactjs, Wordpress, PHP, Mern & Nodejs knowledge

Managed by: @love_data
Download Telegram
๐Ÿš€ ๐—™๐—ฅ๐—˜๐—˜ ๐—™๐—ฟ๐—ฒ๐˜€๐—ต๐—ฒ๐—ฟ ๐—›๐—ถ๐—ฟ๐—ถ๐—ป๐—ด ๐——๐—ฟ๐—ถ๐˜ƒ๐—ฒ | ๐—ง๐—ฒ๐—ฐ๐—ต ๐—ฅ๐—ผ๐—น๐—ฒ๐˜€ ๐—จ๐—ฝ ๐˜๐—ผ โ‚น๐Ÿญ๐Ÿฎ ๐—Ÿ๐—ฃ๐—”!๐Ÿ”ฅ

Internship + Pre-Placement Offer

๐Ÿ’ผ Company: GoComet
๐Ÿ’ฐ Stipend: โ‚น30,000โ€“35,000/Month
๐Ÿš€ PPO: Up to โ‚น12 LPA

๐Ÿ“ Assessment Centres: Pune | Hyderabad | Noida | Chennai | Bangalore

๐Ÿ”— ๐—”๐—ฝ๐—ฝ๐—น๐˜† ๐—ก๐—ผ๐˜„ ๐Ÿ‘‡:

Full Stack Intern:- https://pdlink.in/4z3vF8o

AI First SDET Interns :- https://pdlink.in/4hS1Am2

โณ Limited Hiring Slots Available
โค1๐Ÿฅฑ1
๐Ÿš€ ๐—œ๐—•๐—  ๐—™๐—ฅ๐—˜๐—˜ ๐—–๐—ฒ๐—ฟ๐˜๐—ถ๐—ณ๐—ถ๐—ฐ๐—ฎ๐˜๐—ถ๐—ผ๐—ป ๐—–๐—ผ๐˜‚๐—ฟ๐˜€๐—ฒ๐˜€ ๐ŸŽ“

Upgrade your tech skills with 100% FREE IBM certification courses and build a strong foundation in AI, Data Science, Cloud Computing, SQL, Python, and Machine Learning.

๐ŸŽฏ Perfect For
๐ŸŽ“ Students & Freshers
๐Ÿ‘จโ€๐Ÿ’ป Software Developers
๐Ÿ“Š Data Analysts
๐Ÿค– AI & Data Science Aspirants
๐Ÿ’ผ Working Professionals

๐—˜๐—ป๐—ฟ๐—ผ๐—น๐—น ๐—™๐—ผ๐—ฟ ๐—™๐—ฅ๐—˜๐—˜๐Ÿ‘‡:- 

https://pdlink.in/45KgqDR

๐Ÿ”ฅ Start learning today and prepare yourself for high-paying opportunities in the tech industry!
โค1
๐Ÿš€ JavaScript Interview Questions with Answers โ€” Part 2

11. What is the typeof operator?

The typeof operator is used to determine the data type of a value.

Example:

console.log(typeof "Hello");   // "string"
console.log(typeof 100); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"


Important Interview Point:

console.log(typeof null);


Output: "object"

This is a historical behavior in JavaScript.

12. What are template literals?

Template literals are strings created using backticks ``.

They allow you to easily embed variables and expressions using ${}.

Example:

const name = "Ajay";
const age = 25;

console.log(`My name is ${name} and I am ${age} years old.`);


Output: My name is Ajay and I am 25 years old.

Benefits:

Easy string interpolation

Supports multi-line strings

Allows expressions inside strings

13. What are JavaScript operators?

Operators are symbols used to perform operations on values.

Common Types:

Arithmetic: + - * / % **

Comparison: == === != !== > < >= <=

Logical: && || !

Assignment: = += -= *= /=

Example:

const a = 10;
const b = 5;
console.log(a + b); // 15
console.log(a > b); // true


14. What is the ternary operator?

The ternary operator is a short way of writing an if...else statement.

Syntax:

condition ? valueIfTrue : valueIfFalse;


Example:

const age = 20;
const result = age >= 18 ? "Adult" : "Minor";
console.log(result);


Output: Adult

Equivalent if...else:

if (age >= 18) {
result = "Adult";
} else {
result = "Minor";
}


Interview Tip: Use ternary operators for simple conditions. Avoid deeply nested ternaries because they reduce readability.

15. What is variable hoisting?

Hoisting is JavaScript's behavior of processing declarations before executing the code in their scope.

With var:

console.log(x);
var x = 10;


Output: undefined

The declaration is hoisted, but the assignment happens later.

With let and const:

console.log(x);
let x = 10;


This results in a ReferenceError.

let and const are hoisted but remain in the Temporal Dead Zone (TDZ) until their declaration is reached.

Function declarations are also hoisted:

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


16. What is scope in JavaScript?

Scope determines where a variable can be accessed in a program.

Example:

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


message is accessible inside the function but not outside it.

Main Types:

Global Scope

Function Scope

Block Scope

Module Scope

Understanding scope is essential for closures and avoiding variable conflicts.

17. What are global, function, and block scope?

Global Scope

A variable declared outside functions or blocks can generally be accessed throughout the script.

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


Function Scope

Variables declared with var inside a function are accessible throughout that function.
โค2
function test() {
    var age = 25;
    console.log(age);
}

age

cannot be accessed outside
test()

.

Block Scope
let

and
const

are block-scoped.
if (true) {
    let x = 10;
    const y = 20;
    console.log(x, y);
}

x

and
y

cannot be accessed outside the
if

block.

18. What is strict mode ("use strict")?

Strict mode enables a stricter set of JavaScript rules and helps catch certain programming mistakes.

Example:
"use strict";
x = 10;

This produces a
ReferenceError

because
x

was not declared. 

Without strict mode, older JavaScript behavior could create a global variable in some situations.

Benefits:

Catches common mistakes

Prevents accidental global variables

Makes some unsafe operations throw errors

Helps write cleaner code

19. What are comments in JavaScript?

Comments are text ignored by the JavaScript engine. They are used to explain code or temporarily disable code.

Single-Line Comment:
// This is a comment
console.log("Hello");

Multi-Line Comment:
/*
   This is a
   multi-line comment
*/
console.log("Hello");

Why Use Comments?

โœ… Explain complex logic

โœ… Improve code readability

โœ… Help other developers understand the code

โœ… Document important decisions

20. What are JavaScript modules?

Modules allow you to split JavaScript code into separate, reusable files.

They help organize large applications and prevent unnecessary global variables.

Export:
// math.js
export function add(a, b) {
    return a + b;
}

Import:
// app.js
import { add } from "./math.js";
console.log(add(10, 20));

Types of Exports:

Named exports

Default exports

Default Export:
export default function greet() {
    console.log("Hello");
}

Important Interview Point:

ES Modules use
import

and
export

. They are the standard module system for modern JavaScript.

โค๏ธ Double Tap For Part 3
โค11
๐Ÿš€ JavaScript Interview Questions with Answers โ€” Part 4

31. How do you create objects in JavaScript?

There are several ways to create objects in JavaScript.

1. Object Literal

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


2. new Object()

const user = new Object();
user.name = "Frey";
user.age = 35;


3. Constructor Function

function User(name, age) {
this.name = name;
this.age = age;
}
const user = new User("John", 25);


4. Class

class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const user = new User("John", 25);


Interview Tip:

Object literals are usually preferred for simple objects, while classes or constructor functions are useful when creating many similar objects.

32. What is object destructuring?

Object destructuring allows you to extract properties from an object and store them in variables.

Example:

const user = {
name: "John",
age: 25,
city: "New York"
};
const { name, age } = user;
console.log(name);
console.log(age);


Output:

John

25

Rename Variables:

const { name: userName } = user;
console.log(userName);


Default Value:

const { country = "India" } = user;
console.log(country);


33. What is the spread operator (...)?

The spread operator expands the elements of an iterable or properties of an object.

Array Example:

const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5];
console.log(newNumbers);


Output:

[1, 2, 3, 4, 5]

Object Example:

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

const updatedUser = {
...user,
city: "New York"
};


Common Uses:

โœ… Copy arrays

โœ… Merge arrays

โœ… Copy objects

โœ… Merge objects

โœ… Pass values to functions

34. What is the rest operator?

The rest operator (...) collects multiple values into a single array or object.

Example:

function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(10, 20, 30));


Output: 60

Here, ...numbers collects all arguments into an array.

Important Interview Point:

The same ... syntax has different purposes:

Spread โ†’ expands values: const arr2 = [...arr1];

Rest โ†’ collects values: function test(...args) {}

35. What are default parameters?

Default parameters allow you to provide a default value when an argument is not passed or is undefined.

Example:

function greet(name = "Guest") {
console.log(`Hello ${name}`);
}
greet();


Output: Hello Guest

If a value is provided: greet("Deepika"); โ†’ Hello Deepika

Multiple Defaults:

function createUser(name = "Guest", age = 18) {
console.log(name, age);
}


36. What is optional chaining (?. )

Optional chaining allows you to safely access nested properties without throwing an error when an intermediate value is null or undefined.

Without Optional Chaining:

const user = {};
console.log(user.address.city); // Error


With Optional Chaining:

console.log(user.address?.city); // undefined
โค1
Example with Function: user.getName?.();

The function is called only if getName exists and is callable.

Common Use: Very useful when working with API responses where some properties may be missing.

37. What is nullish coalescing (??)

The nullish coalescing operator returns the right-hand value when the left-hand value is null or undefined.

Example:

const username = null;
console.log(username ?? "Guest");


Output: Guest

Important Difference From ||

|| considers all falsy values: console.log(0 || 100); โ†’ 100

?? only checks null and undefined: console.log(0 ?? 100); โ†’ 0

Interview Tip: Use ?? when 0, false, or "" are valid values that should not be replaced.

38. What are object methods?

An object method is a function stored as a property of an object.

Example:

const user = {
name: "Deepak",
greet() {
console.log(`Hello ${this.name}`);
}
};
user.greet();


Output: Hello Deepak

Another Example:

const calculator = {
add(a, b) { return a + b; },
multiply(a, b) { return a * b; }
};
console.log(calculator.add(10, 20));


39. What is method chaining?

Method chaining means calling multiple methods one after another on the same object or result.

Example:

const result = "javascript"
.toUpperCase()
.split("")
.reverse()
.join("");
console.log(result);


Output: TPIRCSAVAJ

Array Example:

const result = [1, 2, 3, 4, 5]
.filter(num => num % 2 === 0)
.map(num => num * 10);
console.log(result);


Output: [20,40]

Common Uses: Array processing, String manipulation, Promise chains, Libraries such as jQuery

40. What is object freezing and sealing?

JavaScript provides Object.freeze() and Object.seal() to restrict modifications to objects.

Object.freeze()

Prevents: Adding properties, Removing properties, Changing existing properties

const user = { name: "Deepak", age: 25 };
Object.freeze(user);
user.age = 30;
user.city = "Pune";
console.log(user); // unchanged


Object.seal()

Prevents: Adding properties, Removing properties

But existing properties can still be modified.

const user = { name: "Deepak", age: 25 };
Object.seal(user);
user.age = 30;
console.log(user.age); // 30


Key Difference:

Object.freeze(): Cannot add, delete, or modify properties

Object.seal(): Cannot add or delete properties, but can modify existing ones

๐Ÿ”ฅ Interview Tip: Both methods are shallow โ€” nested objects can still be modified unless they are separately frozen/sealed.

โค๏ธ Double Tap For Part 5
โค3
๐Ÿš€ JavaScript Interview Questions with Answers โ€” Part 5

41. How do arrays work in JavaScript?

An array is an ordered collection of values. JS arrays can hold different data types and use zero-based indexing.

Example:

const items = ["Apple", 25, true];
console.log(items[0]); // Apple
console.log(items.length); // 3


Important Points:

โ€ข Index starts at 0

โ€ข Arrays are objects in JavaScript

โ€ข Arrays can grow or shrink dynamically

โ€ข Arrays can contain mixed data types

42. What is the difference between map() and forEach()?

Both iterate over an array, but used differently.

map()

Creates and returns a new array.

const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2); // [2, 4, 6]


forEach()

Executes a function for each element but does not return a new array.

numbers.forEach(num => console.log(num * 2));


Key Difference:

โ€ข map(): Returns a new array. Used for transformation. Can be chained.

โ€ข forEach(): Returns undefined. Used for side effects.

43. What is filter()?

Creates a new array with elements that pass a condition. Original array is not modified.

Example:

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0); // [2, 4]


44. What is reduce()?

Processes an array and produces a single accumulated value.

Example:

const numbers = [10, 20, 30];
const total = numbers.reduce((sum, num) => sum + num, 0); // 60


Common Uses: Calculate totals, averages, count items, group data, build objects.

Interview Tip: Understand the accumulator and current value arguments.

45. What is find()?

Returns the first element that satisfies a condition. Returns undefined if none match.

Example:

const numbers = [10, 20, 30, 40];
const result = numbers.find(num => num > 20); // 30


find() vs filter(): find = first match, filter = all matches.

46. What is findIndex()?

Returns the index of the first element that satisfies a condition. Returns -1 if none match.

Example:

const numbers = [10, 20, 30, 40];
const index = numbers.findIndex(num => num > 20); // 2


47. What is some()?

Checks if at least one element satisfies a condition. Returns Boolean.

Example:

const numbers = [1, 3, 5, 8];
const result = numbers.some(num => num % 2 === 0); // true


48. What is every()?

Checks if all elements satisfy a condition. Returns Boolean.

Example:

const numbers = [2, 4, 6, 8];
const result = numbers.every(num => num % 2 === 0); // true


some() vs every(): some = at least one, every = all.

49. What is the difference between slice() and splice()?

slice()

Returns a portion without modifying the original.

const numbers = [1, 2, 3, 4, 5];
const result = numbers.slice(1, 4); // [2, 3, 4]


splice()

Adds, removes, or replaces elements and modifies the original.

const numbers = [1, 2, 3, 4, 5];
numbers.splice(1, 2); // removes 2 elements at index 1
console.log(numbers); // [1, 4, 5]
โค5๐Ÿ‘Ž2
Key Difference:

โ€ข slice(): Does not modify original. Extracts elements. Returns copied portion.

โ€ข splice(): Modifies original. Adds/removes/replaces. Returns removed elements.

50. What are push(), pop(), shift(), and unshift()?

Methods that modify arrays.

โ€ข push(): Add to END โ†’ arr.push(3)

โ€ข pop(): Remove from END โ†’ arr.pop()

โ€ข unshift(): Add to START โ†’ arr.unshift(0)

โ€ข shift(): Remove from START โ†’ arr.shift()

Quick Memory Trick:

push/pop = END, unshift/shift = START

โค๏ธ Double Tap For Part 6
โค2
โœ… JavaScript Acronyms You MUST Know ๐Ÿ’ป๐Ÿ”ฅ

JS โ†’ JavaScript
ES โ†’ ECMAScript
DOM โ†’ Document Object Model
BOM โ†’ Browser Object Model
JSON โ†’ JavaScript Object Notation
AJAX โ†’ Asynchronous JavaScript And XML
API โ†’ Application Programming Interface
SPA โ†’ Single Page Application
MPA โ†’ Multi Page Application
SSR โ†’ Server Side Rendering
CSR โ†’ Client Side Rendering
TS โ†’ TypeScript
NPM โ†’ Node Package Manager
NPX โ†’ Node Package Execute
CDN โ†’ Content Delivery Network
IIFE โ†’ Immediately Invoked Function Expression
HOF โ†’ Higher Order Function
MVC โ†’ Model View Controller
MVVM โ†’ Model View ViewModel
V8 โ†’ Google JavaScript Engine
REPL โ†’ Read Evaluate Print Loop
CORS โ†’ Cross Origin Resource Sharing
JWT โ†’ JSON Web Token
SSE โ†’ Server Sent Events
WS โ†’ WebSocket

๐Ÿ’ฌ Double Tap โ™ฅ๏ธ For More ๐Ÿš€
โค14๐Ÿ”ฅ4
๐Ÿš€ Full Stack Projects You Should Build (With Source Code)

1๏ธโƒฃ AI SaaS Tool
Learn authentication, subscriptions, APIs & AI integration.

๐Ÿ”— Source Code: https://github.com/ayusshrathore/ai-saas

2๏ธโƒฃ Real-Time Collaborative Code Editor
Just like Google Docs but for coding. Multiple users can edit code simultaneously.

๐Ÿ”— Source Code: https://github.com/Mohitur669/Realtime-Collaborative-Code-Editor

3๏ธโƒฃ Trading Simulator
A virtual stock trading platform to practice trading strategies.

๐Ÿ”— Source Code: https://github.com/nikolatechie/trading-simulator

4๏ธโƒฃ Microservices E-Commerce Platform
Learn scalable architecture using microservices, APIs, and backend systems.

๐Ÿ”— Source Code: https://github.com/ShahandFahad/E-Commerce

5๏ธโƒฃ Real-Time Chat Application
Build a WhatsApp-like chat app with real-time messaging.

๐Ÿ”— Tutorial + Code: https://youtu.be/B_l8nD-bvI0?si=M4N5p1wiPiBW-XA8

6๏ธโƒฃ Developer Portfolio SaaS
Create a platform where developers can generate their own portfolio websites.

๐Ÿ”— Source Code: https://github.com/akhilub/portfolio-saas

7๏ธโƒฃ Job Referral Platform

A platform where users can request and provide job referrals.

๐Ÿ”— Source Code: https://github.com/RutikKulkarni/ReferralNetworkHub

8๏ธโƒฃ Food Delivery App
Build your own Swiggy/Zomato-like full stack application.

๐Ÿ”— Source Code: https://github.com/Mshandev/Food-Delivery

9๏ธโƒฃ Ride Sharing App
Learn how ride booking systems like Uber work.

๐Ÿ”— Source Code: https://github.com/codinggita/ride_share

๐Ÿ”Ÿ Video Streaming Platform
Build your own YouTube-like video streaming platform.

๐Ÿ”— Source Code: https://github.com/soumanpaul/Video-streaming-web-app

โœจ Donโ€™t forget to react to this message for more awesome content like this! ๐Ÿ‘‡

๐Ÿ™ Thank you all for joining! ๐Ÿ’™
โค9๐Ÿ”ฅ1
๐Ÿš€ JavaScript Interview Questions with Answers โ€” Part 6

51. How do you sort arrays?

The sort() method is used to sort the elements of an array.

Sorting Strings

const fruits = ["Banana", "Apple", "Mango"];
fruits.sort();
console.log(fruits);


Output:

["Apple", "Banana", "Mango"]

Sorting Numbers

By default, sort() converts elements to strings, so a comparison function should be used for numbers.

const numbers = [10, 5, 20, 2];
numbers.sort((a, b) => a - b);
console.log(numbers);


Output:

[2, 5, 10, 20]

Descending Order:

numbers.sort((a, b) => b - a);


Interview Tip:

sort() mutates the original array.

52. What is array destructuring?

Array destructuring allows you to extract values from an array and assign them to variables.

Example:

const numbers = [10, 20, 30];
const [a, b, c] = numbers;
console.log(a);
console.log(b);
console.log(c);


Output:

10

20

30

Skipping Values:

const numbers = [10, 20, 30];
const [first, , third] = numbers;
console.log(first, third);


Output:

10 30

Default Values:

const numbers = [10];
const [a, b = 20] = numbers;
console.log(a, b);


Output:

10 20

53. What are Sets?

A Set is a collection of unique values.

Duplicate values are automatically removed.

Example:

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


The Set contains:

{1, 2, 3}

Common Methods:

const numbers = new Set();
numbers.add(10);
numbers.add(20);
console.log(numbers.has(10));
numbers.delete(20);


Convert Set to Array:

const arr = [...numbers];


54. What are Maps?

A Map is a collection of key-value pairs.

Unlike regular objects, a Map can use different data types as keys.

Example:

const users = new Map();
users.set(1, "Deepak");
users.set(2, "John");
console.log(users.get(1));


Output:

Deepak

Common Methods:

users.set(key, value);
users.get(key);
users.has(key);
users.delete(key);
users.clear();


Example:

console.log(users.has(2));


Output:

true

Map vs Object:

Map

โ€ข Any value can be a key

โ€ข Has size property

โ€ข Built-in methods

โ€ข Designed for key-value collections

Object

โ€ข Keys are primarily strings/symbols

โ€ข No built-in size

โ€ข Different object APIs

โ€ข General-purpose objects

55. What are Symbols?

Symbol is a primitive data type used to create unique identifiers.

Example:

const id1 = Symbol("id");
const id2 = Symbol("id");
console.log(id1 === id2);


Output:

false

Even though both have the same description, each Symbol is unique.

Using Symbol as an Object Property:

const id = Symbol("id");
const user = {
name: "Deepak",
[id]: 101
};
console.log(user[id]);


Common Use:

Symbols are useful when you need unique property keys that are unlikely to conflict with other properties.

56. What are generators?

Generators are special functions that can pause and resume execution.

They are created using function* and use the yield keyword.

Example:
โค3
function* numbers() {
yield 1;
yield 2;
yield 3;
}

const generator = numbers();

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


Output:

{ value: 1, done: false }

{ value: 2, done: false }

After all values are consumed:

{ value: 3, done: false }

{ value: undefined, done: true }

Important:

Calling a generator function doesn't immediately execute its body. It returns a generator object.

57. What are iterators?

An iterator is an object that provides a way to access values one at a time using the next() method.

Example:

const numbers = [10, 20, 30];
const iterator = numbers[Symbol.iterator]();

console.log(iterator.next());
console.log(iterator.next());


Output:

{ value: 10, done: false }

{ value: 20, done: false }

The iterator eventually returns:

{ value: undefined, done: true }

Common Iterables:

โ€ข Arrays

โ€ข Strings

โ€ข Maps

โ€ข Sets

That's why they can be used with for...of.

for (const number of numbers) {
console.log(number);
}


58. What is destructuring assignment?

Destructuring assignment allows values to be extracted from arrays or objects and assigned to variables.

Object Example:

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

const { name, age } = user;


Array Example:

const numbers = [10, 20];
const [a, b] = numbers;


Why Use It?

It makes code shorter and easier to read, especially when working with API responses and function parameters.

59. What is dynamic import?

Dynamic import allows a JavaScript module to be loaded when it is needed, instead of loading it immediately.

It uses: import()

Example:

async function loadModule() {
const module = await import("./math.js");
console.log(module.add(10, 20));
}


Important:

Unlike a static import:

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


dynamic imports return a Promise.

Common Uses:

โ€ข Lazy loading

โ€ข Code splitting

โ€ข Loading features only when required

โ€ข Improving initial page performance

60. What are ES6 modules?

ES6 modules provide a standard way to divide JavaScript applications into separate files.

They use export and import.

Export:

// math.js
export function add(a, b) {
return a + b;
}


Import:

// app.js
import { add } from "./math.js";
console.log(add(10, 20));


Default Export:

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


Import:

import greet from "./greet.js";


Benefits:

โœ… Code organization

โœ… Reusability

โœ… Encapsulation

โœ… Easier maintenance

โœ… Avoids unnecessary global variables

โค๏ธ Double Tap For Part 7
โค2๐Ÿ‘1
๐Ÿš€ JavaScript Interview Questions with Answers โ€” Part 8

71. What is fetch()?

fetch() is a modern JavaScript API used to make HTTP requests and communicate with servers.

It returns a Promise.

Example:

fetch("https://api.example.com/users")
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.log(error);
});


Using async/await:

async function getUsers() {
try {
const response = await fetch(
"https://api.example.com/users"
);
const data = await response.json();
console.log(data);
} catch (error) {
console.log(error);
}
}


Interview Tip:

fetch() rejects its Promise for network-level failures, but an HTTP error such as 404 or 500 does not automatically reject it. You should check response.ok.

72. What is AJAX?

AJAX stands for Asynchronous JavaScript and XML.

It is a technique for communicating with a server and updating parts of a webpage without reloading the entire page.

Despite the name, AJAX doesn't require XML. Modern applications commonly exchange JSON.

Example:

A webpage can request:

User data โ†’ Server
โ†“
JSON
โ†“
JavaScript
โ†“
Update webpage


Modern Approach:

Today, fetch() is commonly used instead of the older XMLHttpRequest API.

73. What are Web APIs?

Web APIs are browser-provided interfaces that allow JavaScript to interact with browser features and the environment.

Examples include:

โ€ข fetch()

โ€ข setTimeout()

โ€ข DOM APIs

โ€ข Local Storage

โ€ข Geolocation API

โ€ข Web Workers

โ€ข Clipboard API

Example:

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


The timer functionality is provided by the host environment, such as a browser or Node.js runtime, rather than being part of the JavaScript language itself.

Interview Tip:

Don't confuse JavaScript language features with browser Web APIs.

74. What is setTimeout()?

setTimeout() schedules a function to run after a specified delay.

Example:

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


The callback becomes eligible to run after approximately 2 seconds.

Important:

The delay is not a guarantee that the function executes exactly at that time.

It may execute later if the JavaScript runtime is busy.

75. What is setInterval()?

setInterval() repeatedly schedules a function at approximately specified intervals.

Example:

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


The callback runs approximately every second until the interval is cancelled.

Stop It:

clearInterval(interval);


Common Uses:

โ€ข Timers

โ€ข Polling

โ€ข Repeated UI updates

โ€ข Periodic tasks

76. What is clearTimeout()?

clearTimeout() cancels a timeout that was previously scheduled using setTimeout().

Example:

const timer = setTimeout(() => {
console.log("Hello");
}, 5000);

clearTimeout(timer);


The callback will not execute because the timeout was cancelled before it became eligible to run.

Common Use:

Useful when you need to cancel a scheduled action.

77. What is clearInterval()?

clearInterval() stops an interval created using setInterval().

Example:
let count = 0;

const interval = setInterval(() => {
count++;
console.log(count);
if (count === 5) {
clearInterval(interval);
}
}, 1000);


Output:

1

2

3

4

5

After 5, the interval is stopped.

78. What is callback hell?

Callback hell occurs when multiple asynchronous operations are nested inside one another, making code difficult to read and maintain.

Example:

getUser(user => {
getOrders(user, orders => {
getPayment(orders, payment => {
processPayment(payment, result => {
console.log(result);
});
});
});
});


This creates deeply nested code.

Problems:

โŒ Difficult to read

โŒ Difficult to debug

โŒ Difficult to maintain

โŒ Error handling becomes complicated

79. How do you avoid callback hell?

Several approaches can make asynchronous code cleaner.

1. Use Promises

getUser()
.then(getOrders)
.then(getPayment)
.then(processPayment)
.catch(handleError);


2. Use async/await

async function process() {
try {
const user = await getUser();
const orders = await getOrders(user);
const payment = await getPayment(orders);
await processPayment(payment);
} catch (error) {
console.log(error);
}
}


3. Break large functions into smaller functions

Instead of putting everything into one deeply nested callback, separate responsibilities into reusable functions.

Interview Tip:

For modern JavaScript, Promises and async/await are the most common solutions.

80. What are microtasks and macrotasks?

This is an important advanced JavaScript interview topic.

The JavaScript runtime has different queues for asynchronous work.

Microtasks

Examples include:

โ€ข Promise callbacks

โ€ข queueMicrotask()

โ€ข MutationObserver callbacks in browsers

Macrotasks / Tasks

Common examples include:

โ€ข setTimeout()

โ€ข setInterval()

โ€ข Some browser events

Example:

console.log("Start");

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

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

console.log("End");


Output:

Start

End

Promise

Timeout

Why?

After the synchronous code finishes, the runtime processes available microtasks before moving to the next task.

So:

Synchronous code
โ†“
Microtasks
โ†“
Next task / macrotask


โค๏ธ Double Tap For Part 9
โค1
๐Ÿš€ JavaScript Interview Questions with Answers โ€” Part 10

91. What is throttling?

Throttling limits how frequently a function can execute within a given time interval.

Even if an event fires many times, the function is allowed to execute at most once during each interval.

Example:

function throttle(callback, delay) {
let lastTime = 0;
return function(...args) {
const now = Date.now();
if (now - lastTime >= delay) {
lastTime = now;
callback.apply(this, args);
}
};
}


Common Uses:

โ€ข Scroll events

โ€ข Mouse movement

โ€ข Window resizing

โ€ข Continuous user interactions

Debounce vs Throttle:

Debounce โ†’ Execute after activity stops

Throttle โ†’ Execute at controlled intervals

92. What is memoization?

Memoization is an optimization technique where the result of a function is cached so that the same calculation doesn't have to be performed again.

Example:

function memoize(fn) {
const cache = new Map();
return function(n) {
if (cache.has(n)) {
return cache.get(n);
}
const result = fn(n);
cache.set(n, result);
return result;
};
}


Example Usage:

function square(n) {
console.log("Calculating...");
return n * n;
}

const memoizedSquare = memoize(square);

console.log(memoizedSquare(5));
console.log(memoizedSquare(5));


The first call performs the calculation.

The second call can use the cached result.

Benefits:

โœ… Faster repeated calculations

โœ… Avoids unnecessary work

Drawback:

โŒ Uses additional memory for cached results.

93. What is currying?

Currying transforms a function that takes multiple arguments into a sequence of functions that each take one argument.

Normal Function:

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

console.log(add(1, 2, 3));


Curried Function:

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


Usage:

console.log(add(1)(2)(3));


Output:

6


Arrow Function Version:

const add = a => b => c => a + b + c;


Common Uses:

โ€ข Functional programming

โ€ข Creating reusable functions

โ€ข Partial application

โ€ข Configuration-based functions

94. What is prototype inheritance?

JavaScript uses objects as the foundation of its inheritance system.

Objects can access properties and methods through their prototype chain.

Example:

const animal = {
speak() {
console.log("Animal speaks");
}
};

const dog = Object.create(animal);

dog.speak();


Although dog doesn't directly contain speak(), it can access the method through its prototype.

Prototype Chain:

dog

โ†“

animal

โ†“

Object.prototype

โ†“

null

JavaScript searches this chain when a property isn't found directly on the object.

95. What is prototypal inheritance?

Prototypal inheritance is JavaScript's mechanism for allowing one object to inherit behavior from another object through the prototype chain.

Example:

const person = {
greet() {
console.log("Hello");
}
};

const student = Object.create(person);

student.study = function() {
console.log("Studying");
};

student.greet();
student.study();


Here:

student has its own study() method.

greet() comes from its prototype, person.

96. What are classes in JavaScript?

Classes provide a cleaner syntax for creating objects and implementing object-oriented programming patterns.

Classes were introduced in ES6.

Example:
โค2
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}

greet() {
console.log(`Hello, I am ${this.name}`);
}
}

const person = new Person("Deepak", 25);

person.greet();


Output:

Hello, I am Deepak

Important:

JavaScript classes are built on top of JavaScript's prototype-based inheritance.

Classes Support:

โ€ข Constructors

โ€ข Methods

โ€ข Inheritance

โ€ข Getters and setters

โ€ข Static methods

โ€ข Private fields

97. What is garbage collection?

Garbage collection is the automatic process of identifying and reclaiming memory that is no longer reachable or needed by a JavaScript program.

Developers don't normally manually free JavaScript objects.

Example:

let user = {
name: "Deepak"
};

user = null;


If the original object is no longer reachable from the program, it can eventually become eligible for garbage collection.

Important:

Garbage collection timing is determined by the JavaScript engine. You cannot normally force it from standard JavaScript code.

98. How does JavaScript manage memory?

JavaScript automatically manages memory using mechanisms such as:

1. Memory allocation

2. Program execution

3. Garbage collection

Simplified Process:

Create value

โ†“

Memory allocated

โ†“

Program uses value

โ†“

Value becomes unreachable

โ†“

Garbage collector

โ†“

Memory can be reclaimed

What is a Memory Leak?

A memory leak occurs when a program unintentionally keeps references to objects that it no longer needs.

Common Causes:

โ€ข Unremoved event listeners

โ€ข Unnecessary global variables

โ€ข Timers that aren't cleared

โ€ข Large objects retained in closures

โ€ข Growing caches without limits

Example:

const cache = [];

function addData(data) {
cache.push(data);
}


If cache keeps growing indefinitely, it can consume increasing amounts of memory.

99. What are CommonJS and ES Modules?

Both are module systems used in JavaScript applications.

CommonJS

Commonly associated with Node.js and uses require() and module.exports.

// math.js
function add(a, b) {
return a + b;
}

module.exports = { add };


Import:

const { add } = require("./math");


ES Modules

The standardized JavaScript module system uses import and export.

// math.js
export function add(a, b) {
return a + b;
}


Import:

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


Modern JavaScript development commonly uses ES Modules, while CommonJS remains important when working with existing Node.js projects.

100. What are the latest JavaScript features introduced in ES2025 and beyond?

JavaScript continues to evolve through yearly ECMAScript releases.

For ES2025 (ECMAScript 2025), notable standardized additions include:

๐Ÿ”ฅ Iterator Helpers

Methods such as:

iterator.map(...)

iterator.filter(...)

iterator.take(...)

allow lazy processing of iterator values.

๐Ÿ”ฅ Iterator.from()

Allows an object to be converted into an iterator.

const iterator = Iterator.from([1, 2, 3]);


๐Ÿ”ฅ Set Methods

Modern Set operations include methods such as:

โ€ข union()

โ€ข intersection()

โ€ข difference()

โ€ข symmetricDifference()

Example:

const a = new Set([1, 2, 3]);
const b = new Set([3, 4, 5]);

const result = a.union(b);

console.log(result);
โค2
๐Ÿ”ฅ Regular Expression Improvements

ES2025 also introduced improvements to regular expressions, including support for enhanced Unicode-related matching capabilities.

๐Ÿ”ฅ Promise.try()

Promise.try() provides a convenient way to turn a synchronous function call into a Promise-based operation.

Promise.try(() => {
return someFunction();
});


โš ๏ธ Important Interview Point

JavaScript features are standardized through the ECMAScript specification, and browser/Node.js support can vary by feature and version.

So when discussing "latest JavaScript," distinguish between:

Standardized features

โ†’ Officially included in an ECMAScript release.

Proposed features

โ†’ Still moving through the TC39 proposal process.

Runtime support

โ†’ Whether a particular browser or Node.js version actually supports the feature.

Double Tap โค๏ธ For More
โค2
Free Resources to Learn Each Tech Stack ๐Ÿง โœจ

No excuses. Everything you need is free!

1. Frontend Development
โฏ freeCodeCamp.org โ€“ HTML, CSS, JS
โฏ MDN Web Docs โ€“ Best docs for web tech
โฏ Frontend Mentor โ€“ Real-world challenges
โฏ CSS Tricks โ€“ CSS deep dives
โฏ YouTube: Kevin Powell, Web Dev Simplified

โ€”

2. Backend Development
โฏ Node.js Docs
โฏ Django Girls Tutorial
โฏ The Odin Project โ€“ Full Stack
โฏ Spring Boot Guides
โฏ YouTube: Amigoscode, CodeWithHarry (Hindi), Tech With Tim

โ€”

3. Full-Stack Development
โฏ Full Stack Open โ€“ React + Node
โฏ The Odin Project
โฏ CS50 Web โ€“ Harvardโ€™s free course
โฏ YouTube: Traversy Media, Clever Programmer, JavaScript Mastery

โ€”

4. Data Analytics
โฏ Kaggle Learn โ€“ Python, SQL, Viz
โฏ Maven Analytics โ€“ Free Power BI/Tableau projects
โฏ Google Data Analytics Course
โฏ W3Schools SQL
โฏ YouTube: Luke Barousse, Alex The Analyst

โ€”

5. Machine Learning
โฏ Googleโ€™s ML Crash Course
โฏ fast.ai โ€“ Deep learning made easy
โฏ Kaggle Courses โ€“ End-to-end ML
โฏ Coursera โ€“ Andrew Ng
โฏ YouTube: StatQuest, Krish Naik, Codebasics

โ€”

6. DevOps
โฏ KodeKloud โ€“ Docker, K8s, Ansible
โฏ Learn Git Branching
โฏ Katacoda โ€“ Interactive Linux & DevOps
โฏ Roadmap.sh โ€“ What to learn
โฏ YouTube: TechWorld with Nana, Nana Janashia
โค8
๐Ÿš€ JavaScript Tips โ€” Part 2

1๏ธโƒฃ Use strict mode when appropriate

Strict mode helps catch certain common mistakes and prevents some unsafe behaviors.

"use strict";


2๏ธโƒฃ Use optional chaining for uncertain data

When working with API responses or nested objects, optional chaining can prevent errors when a property doesn't exist.

const user = {};
console.log(user.address?.city);


3๏ธโƒฃ Understand || vs ??

They behave differently when dealing with falsy values.

const count = 0;
console.log(count || 10); // 10

console.log(count ?? 10); // 0


Use ?? when 0, false, or an empty string are valid values.

4๏ธโƒฃ Don't overuse ternary operators

Ternary operators are great for simple conditions.

const age = 20;
const status = age >= 18 ? "Adult" : "Minor";


For complicated logic, a normal if...else is usually easier to read.

5๏ธโƒฃ Use destructuring when it improves readability

Destructuring can make working with objects and arrays cleaner.

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


6๏ธโƒฃ Understand spread vs rest

The same ... syntax has two different purposes.

Spread โ†’ expands values

const numbers = [1, 2, 3];
const copy = [...numbers];


Rest โ†’ collects values

function sum(...numbers) {
return numbers.length;
}


7๏ธโƒฃ Don't rely on implicit type coercion

JavaScript can automatically convert types, sometimes producing surprising results.

console.log("10" + 5); // "105"
console.log("10" - 5); // 5


Be explicit when conversion matters.

8๏ธโƒฃ Handle asynchronous errors properly

Don't assume every API request or asynchronous operation will succeed.

async function getData() {
try {
const response = await fetch("/api/data");
const data = await response.json();
return data;
} catch (error) {
console.error("Request failed:", error);
}
}


9๏ธโƒฃ Don't block the main thread

Heavy calculations or large amounts of synchronous work can make a web application unresponsive.

For expensive tasks, consider:

โ€ข Breaking work into smaller tasks

โ€ข Web Workers

โ€ข Efficient algorithms

โ€ข Avoiding unnecessary rendering

๐Ÿ”Ÿ Use debounce and throttle appropriately

These techniques are useful when an event fires repeatedly.

Debounce โ†’ Run after activity stops.

Throttle โ†’ Limit execution to a controlled frequency.

Common use cases: Search inputs, Scrolling, Resizing, Mouse movement

1๏ธโƒฃ1๏ธโƒฃ Use const objects carefully

const prevents reassignment of the variable, but it doesn't make the object immutable.

const user = {
name: "Alex"
};
user.name = "Sam"; // Allowed


Understanding this distinction is important.

1๏ธโƒฃ2๏ธโƒฃ Don't blindly use JSON.parse() and JSON.stringify()

They are useful for JSON data, but they aren't universal deep-copy solutions. They can lose or alter certain JavaScript values and don't preserve all object types.

For structured cloning, consider structuredClone() when appropriate.

1๏ธโƒฃ3๏ธโƒฃ Use === consistently

Strict equality makes your comparisons easier to reason about.

if (status === "active") {
console.log("User is active");
}
โค4
1๏ธโƒฃ4๏ธโƒฃ Learn the event loop

Understanding the event loop helps you predict the execution order of: Synchronous code, Promise callbacks, Timers, Events

This is especially important for JavaScript interviews.

1๏ธโƒฃ5๏ธโƒฃ Practice reading error messages

Don't immediately search for a solution when your code fails.

First understand: What error occurred โ†’ Where did it occur โ†’ Why did it occur โ†’ How can it be fixed?

๐Ÿ”ฅ Golden Tip: The faster you become at understanding your own errors, the faster you'll become at solving JavaScript problems.

Double Tap โค๏ธ For More Useful Tips
โค5