0% found this document useful (0 votes)
4 views86 pages

JavaScript Handbook

The JavaScript Coding Handbook provides a comprehensive overview of JavaScript, covering its history, key features, and various applications in web, mobile, and desktop development. It explains fundamental concepts such as variables, data types, operators, and conditional statements, along with practical examples and interview questions. The document serves as a guide for beginners to advanced learners in mastering JavaScript programming.

Uploaded by

kunalpatil29th
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views86 pages

JavaScript Handbook

The JavaScript Coding Handbook provides a comprehensive overview of JavaScript, covering its history, key features, and various applications in web, mobile, and desktop development. It explains fundamental concepts such as variables, data types, operators, and conditional statements, along with practical examples and interview questions. The document serves as a guide for beginners to advanced learners in mastering JavaScript programming.

Uploaded by

kunalpatil29th
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript Coding Handbook

From Beginner to Advanced

1. Introduction to JavaScript
JavaScript is a high-level, interpreted programming language primarily used
for creating interactive and dynamic web content. Alongside HTML and CSS,
it is one of the core technologies of the World Wide Web. Over the years,
JavaScript has evolved from a client-side scripting language to a versatile
language capable of server-side development ([Link]), mobile app
development (React Native), and even desktop applications (Electron).

What is JavaScript?

JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled


programming language with first-class functions. While it is most well-known
as the scripting language for web pages, many non-browser environments
also use it, such as [Link], Apache CouchDB, and Adobe Acrobat.
JavaScript is a multi-paradigm language, supporting event-driven, functional,
and imperative programming styles.

Key Characteristics:

• High-level: Abstracts away complex computer details, making it easier to


write code.
• Interpreted/JIT Compiled: Code is executed line by line by an
interpreter, or compiled just before execution for performance.
• Dynamic: Supports dynamic typing, meaning variable types are
determined at runtime.
• Client-side: Originally designed to run in web browsers, enabling
interactive web pages.
• Versatile: Used for front-end, back-end, mobile, and desktop
development.

History of JavaScript

JavaScript was created by Brendan Eich at Netscape Communications in


1995. It was initially named Mocha, then LiveScript, and finally JavaScript.
The name change was a marketing move to capitalize on the popularity of
Java at the time, despite the languages having very little in common beyond
C-like syntax.

Year Event
Brendan Eich creates JavaScript (initially Mocha, then LiveScript) at
1995
Netscape.
Netscape submits JavaScript to ECMA International for
1996
standardization.
1997 ECMAScript 1 (ES1) is released, standardizing JavaScript.
ECMAScript 3 (ES3) is released, adding regular expressions, better
1999
string handling, and new control statements.
ECMAScript 5 (ES5) is released, introducing strict mode, JSON
2009
support, and new array methods.
ECMAScript 2015 (ES6/ES2015) is a major release, adding classes,
2015
modules, arrow functions, promises, let/const, and more.
New ECMAScript versions are released every year, adding new
Annually
features and improvements.

How JavaScript Works in a Browser

When a web page loads, the browser's JavaScript engine (e.g., V8 for
Chrome, SpiderMonkey for Firefox) reads and executes the JavaScript code.
This code can manipulate the Document Object Model (DOM), respond to
user events, fetch data from servers, and much more, making web pages
interactive.
Example: Simple JavaScript in HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"
<title>My First JS Page</title>
</head>
<body>
<h1>Hello, JavaScript!</h1>
<button onclick="alert('Hello from JavaScript!');">Click Me</button>

<script>
// This is an inline JavaScript comment
[Link]("Page loaded successfully!");
</script>
</body>
</html>

Where is JavaScript Used?

• Front-end Web Development: Adding interactivity to websites (e.g.,


animations, form validation, dynamic content loading).
• Back-end Web Development: With [Link], JavaScript can be used to
build scalable server-side applications and APIs.
• Mobile App Development: Frameworks like React Native and
NativeScript allow building cross-platform mobile apps.
• Desktop App Development: Tools like Electron enable building desktop
applications using web technologies.
• Game Development: Libraries like [Link] and [Link] are used for
creating browser-based games.
Interview Questions

1. What is JavaScript, and what are its key features?


2. How does JavaScript differ from Java?
3. Explain the role of JavaScript in web development.
4. What is ECMAScript?
5. Can JavaScript be used for backend development? If so, how?

Multiple Choice Questions (MCQs)

1. Which company developed JavaScript? a) Microsoft b) Google c)


Netscape d) Apple Answer: c) Netscape

2. What is the primary use of JavaScript? a) Styling web pages b)


Structuring web content c) Adding interactivity to web pages d)
Database management Answer: c) Adding interactivity to web pages

3. Which of the following is NOT a characteristic of JavaScript? a) High-


level b) Statically typed c) Interpreted d) Multi-paradigm Answer: b)
Statically typed

Practice Program: Simple Greeting

Write a JavaScript program that prompts the user for their name and then
displays a personalized greeting message on the console.

// Practice Program: Simple Greeting

// 1. Prompt the user for their name


const userName = prompt("What is your name?");

// 2. Display a personalized greeting


if (userName) {
[Link](`Hello, ${userName}! Welcome to JavaScript.`);
} else {
[Link]("Hello there! Please provide your name next time.");
}

2. Variables (var, let, const)


Variables are containers for storing data values. In JavaScript, there are three
ways to declare a variable: var, let, and const. Understanding the
differences between them is crucial for writing modern, bug-free code.

The var Keyword

Before ES6 (2015), var was the only way to declare variables. It has function
scope or global scope, but not block scope. This can sometimes lead to
unexpected behavior.

• Scope: Function-scoped or globally scoped.


• Hoisting: Variables declared with var are hoisted to the top of their
scope and initialized with undefined.
• Re-declaration: Allowed within the same scope.

var name = "Alice";


var name = "Bob"; // Allowed
[Link](name); // Output: Bob

if (true) {
var age = 30;
}
[Link](age); // Output: 30 (Accessible outside the block)
The let Keyword

Introduced in ES6, let is the modern way to declare variables that may
change their value later. It provides block scope, which is more predictable
than var.

• Scope: Block-scoped (confined to the {} where it is defined).


• Hoisting: Hoisted, but not initialized. Accessing it before declaration
results in a ReferenceError (Temporal Dead Zone).
• Re-declaration: Not allowed within the same scope.

let city = "New York";


// let city = "London"; // SyntaxError: Identifier 'city' has already bee
city = "London"; // Re-assignment is allowed

if (true) {
let country = "UK";
[Link](country); // Output: UK
}
// [Link](country); // ReferenceError: country is not defined

The const Keyword

Also introduced in ES6, const is used to declare variables whose values


should not change (constants). Like let, it is block-scoped.

• Scope: Block-scoped.
• Hoisting: Hoisted, but not initialized (Temporal Dead Zone).
• Re-declaration: Not allowed.
• Re-assignment: Not allowed. Must be initialized at the time of
declaration.

const PI = 3.14159;
// PI = 3.14; // TypeError: Assignment to constant variable.
// Note: For objects and arrays, the reference is constant, but propertie
const user = { name: "John" };
[Link] = "Jane"; // Allowed
[Link]([Link]); // Output: Jane

Comparison Table

Feature var let const

Scope Function / Global Block Block


Yes (initialized to Yes (Temporal Yes (Temporal
Hoisting
undefined) Dead Zone) Dead Zone)
Re-
Yes No No
declaration
Re-
Yes Yes No
assignment

Interview Questions

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


2. Explain the concept of "hoisting" in JavaScript.
3. What is the Temporal Dead Zone (TDZ)?
4. Can you modify the properties of an object declared with const?

Multiple Choice Questions (MCQs)

1. Which keyword provides block scope? a) var b) let c) const d) Both b


and c Answer: d) Both b and c

2. What happens if you try to re-assign a value to a const variable? a) It


silently fails. b) It throws a TypeError. c) It updates the value. d) It
throws a SyntaxError. Answer: b) It throws a TypeError.
3. Data Types
JavaScript is a dynamically typed language, meaning you don't have to
specify the data type of a variable when you declare it. The data type is
determined automatically during execution.

JavaScript data types are divided into two main categories: Primitive and Non-
Primitive (Reference) types.

Primitive Data Types

Primitive types hold a single, simple value. They are immutable (cannot be
changed).

1. String: Represents a sequence of characters. Enclosed in single quotes,


double quotes, or backticks. javascript let greeting = "Hello";
let name = 'Alice'; let message = `Welcome, ${name}`; //
Template literal
2. Number: Represents both integer and floating-point numbers.
javascript let age = 25; let price = 19.99;
3. BigInt: Used for integers larger than the Number type can safely
represent. javascript let largeNumber = 9007199254740991n;
4. Boolean: Represents a logical entity and can have two values: true or
false. javascript let isLogged = true; let hasError =
false;
5. Undefined: A variable that has been declared but not assigned a value
has the value undefined. javascript let x; [Link](x); //
Output: undefined
6. Null: Represents the intentional absence of any object value. It is treated
as a falsy value. javascript let user = null;
7. Symbol: Introduced in ES6, represents a unique and immutable
identifier. javascript let sym1 = Symbol("id"); let sym2 =
Symbol("id"); [Link](sym1 === sym2); // Output:
false
Non-Primitive (Reference) Data Types

Non-primitive types can hold collections of values or complex entities. They


are mutable.

1. Object: A collection of key-value pairs. javascript let person =


{ firstName: "John", lastName: "Doe", age: 30 };
2. Array: A special type of object used to store multiple values in a single
variable. javascript let colors = ["red", "green", "blue"];
3. Function: A callable object that executes a block of code. javascript
function greet() { [Link]("Hello!"); }

The typeof Operator

You can use the typeof operator to find the data type of a JavaScript
variable.

[Link](typeof "John"); // Output: "string"


[Link](typeof 3.14); // Output: "number"
[Link](typeof true); // Output: "boolean"
[Link](typeof undefined); // Output: "undefined"
[Link](typeof null); // Output: "object" (This is a known bug in J

Interview Questions

1. What are the primitive data types in JavaScript?


2. What is the difference between null and undefined?
3. Why does typeof null return "object"?
4. What is a Symbol, and when would you use it?

Multiple Choice Questions (MCQs)

1. Which of the following is NOT a primitive data type? a) String b) Number


c) Object d) Boolean Answer: c) Object
2. What is the output of typeof undefined? a) "null" b) "undefined" c)
"object" d) "string" Answer: b) "undefined"

4. Operators
Operators are symbols that perform operations on operands (values or
variables). JavaScript supports various types of operators.

1. Arithmetic Operators

Used to perform mathematical calculations.

• + (Addition)
• - (Subtraction)
• * (Multiplication)
• / (Division)
• % (Modulus/Remainder)
• ** (Exponentiation)
• ++ (Increment)
• -- (Decrement)

let a = 10;
let b = 3;
[Link](a + b); // 13
[Link](a % b); // 1

2. Assignment Operators

Used to assign values to variables.

• = (Assign)
• += (Add and assign)
• -= (Subtract and assign)
• *= (Multiply and assign)
• /= (Divide and assign)

let x = 5;
x += 3; // Equivalent to x = x + 3
[Link](x); // 8

3. Comparison Operators

Used to compare two values. They return a boolean (true or false).

• == (Equal to - checks value only)


• === (Strict equal to - checks value and type)
• != (Not equal to)
• !== (Strict not equal to)
• > (Greater than)
• < (Less than)
• >= (Greater than or equal to)
• <= (Less than or equal to)

[Link](5 == "5"); // true (type coercion happens)


[Link](5 === "5"); // false (different types)

4. Logical Operators

Used to determine the logic between variables or values.

• && (Logical AND): Returns true if both operands are true.


• || (Logical OR): Returns true if at least one operand is true.
• ! (Logical NOT): Reverses the boolean value.

let isAdult = true;


let hasID = false;
[Link](isAdult && hasID); // false
[Link](isAdult || hasID); // true

5. String Operators

The + operator can also be used to concatenate (join) strings.

let text1 = "Hello";


let text2 = "World";
[Link](text1 + " " + text2); // "Hello World"

6. Ternary Operator

A shorthand for an if...else statement. Syntax: condition ?


exprIfTrue : exprIfFalse

let age = 20;


let status = (age >= 18) ? "Adult" : "Minor";
[Link](status); // "Adult"

Interview Questions

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


2. Explain the concept of type coercion in JavaScript.
3. How does the ternary operator work? Provide an example.

Multiple Choice Questions (MCQs)

1. What is the output of 5 + "5" in JavaScript? a) 10 b) "55" c) NaN d)


Error Answer: b) "55"
2. Which operator is used for strict equality comparison? a) = b) == c) ===
d) !== Answer: c) ===

5. Conditional Statements
Conditional statements are used to perform different actions based on
different conditions.

if Statement

Executes a block of code if a specified condition is true.

let hour = 10;


if (hour < 12) {
[Link]("Good morning!");
}

if...else Statement

Executes one block of code if the condition is true, and another block if it is
false.

let isRaining = true;


if (isRaining) {
[Link]("Take an umbrella.");
} else {
[Link]("Enjoy the sunshine.");
}
if...else if...else Statement

Used to specify a new condition to test if the first condition is false.

let score = 85;


if (score >= 90) {
[Link]("Grade: A");
} else if (score >= 80) {
[Link]("Grade: B");
} else {
[Link]("Grade: C or below");
}

switch Statement

Used to perform different actions based on different conditions. It is often


used as an alternative to multiple if...else if statements when comparing
a single variable against many values.

let day = 3;
let dayName;

switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
default:
dayName = "Invalid day";
}
[Link](dayName); // Output: Wednesday

Note: The break keyword is crucial to stop the execution from falling through
to the next cases.

Interview Questions

1. When would you use a switch statement instead of if...else if?


2. What happens if you forget the break statement in a switch case?
3. What are "truthy" and "falsy" values in JavaScript?

Multiple Choice Questions (MCQs)

1. Which statement is used to execute code if a condition is false? a) if b)


else c) else if d) switch Answer: b) else

2. What is the purpose of the default clause in a switch statement? a)


To specify the first case to check. b) To execute code if no cases match.
c) To break out of the switch block. d) It is mandatory for every switch
statement. Answer: b) To execute code if no cases match.

6. Loops
Loops are used to execute a block of code repeatedly as long as a specified
condition is true. They are essential for iterating over arrays or performing
repetitive tasks.

for Loop

The most common loop, used when you know in advance how many times
the script should run.
Syntax: for (initialization; condition; increment/decrement)
{ ... }

for (let i = 0; i < 5; i++) {


[Link]("Iteration number: " + i);
}

while Loop

Loops through a block of code as long as a specified condition is true.

let count = 0;
while (count < 3) {
[Link]("Count is: " + count);
count++;
}

do...while Loop

Similar to the while loop, but it will execute the code block at least once
before checking the condition.

let j = 5;
do {
[Link]("Value of j: " + j);
j++;
} while (j < 5); // Executes once even though condition is false initiall
for...in Loop

Used to loop through the properties of an object.

const person = { fname: "John", lname: "Doe", age: 25 };


for (let key in person) {
[Link](key + ": " + person[key]);
}

for...of Loop

Introduced in ES6, used to loop over iterable objects like arrays, strings,
maps, etc.

const cars = ["BMW", "Volvo", "Mini"];


for (let car of cars) {
[Link](car);
}

Loop Control Statements

• break: Exits the loop entirely.


• continue: Skips the current iteration and continues with the next one.

for (let i = 0; i < 5; i++) {


if (i === 2) continue; // Skips 2
if (i === 4) break; // Stops at 4
[Link](i); // Outputs: 0, 1, 3
}
Interview Questions

1. What is the difference between a while loop and a do...while loop?


2. When should you use for...in vs for...of?
3. How do break and continue differ?

Multiple Choice Questions (MCQs)

1. Which loop is guaranteed to execute at least once? a) for b) while c)


do...while d) for...in Answer: c) do...while

2. Which loop is best suited for iterating over the values of an array? a)
for...in b) for...of c) while d) do...while Answer: b) for...of

7. Functions
A JavaScript function is a block of code designed to perform a particular task.
Functions are executed when they are invoked (called).

Function Declaration

The standard way to define a function. These are hoisted, meaning they can
be called before they are defined in the code.

function greet(name) {
return "Hello, " + name + "!";
}
[Link](greet("Alice"));

Function Expression

A function can also be defined using an expression and stored in a variable.


These are not hoisted.
const multiply = function(a, b) {
return a * b;
};
[Link](multiply(4, 5)); // 20

Arrow Functions (ES6)

A shorter syntax for writing function expressions. They do not have their own
this binding.

// Standard arrow function


const add = (x, y) => {
return x + y;
};

// Implicit return (if only one statement)


const square = n => n * n;

[Link](add(2, 3)); // 5
[Link](square(4)); // 16

Parameters and Arguments

• Parameters: The names listed in the function definition.


• Arguments: The real values passed to the function when it is called.

Default Parameters (ES6)

You can assign default values to parameters if no argument is provided.

function welcome(name = "Guest") {


[Link]("Welcome, " + name);
}
welcome(); // Welcome, Guest
welcome("Bob"); // Welcome, Bob

Return Statement

When JavaScript reaches a return statement, the function stops executing


and returns the specified value to the caller.

Interview Questions

1. What is the difference between a function declaration and a function


expression?
2. Explain arrow functions and how they differ from regular functions
regarding the this keyword.
3. What are default parameters?
4. What is an IIFE (Immediately Invoked Function Expression)?

Multiple Choice Questions (MCQs)

1. Which of the following is a valid arrow function syntax? a) function =>


{} b) () => {} c) => function {} d) arrow() {} Answer: b) () =>
{}

2. Are function declarations hoisted in JavaScript? a) Yes b) No Answer: a)


Yes

8. Arrays
An array is a special variable that can hold more than one value at a time. It
is an ordered collection of data.

Creating Arrays
// Using array literal (recommended)
const fruits = ["Apple", "Banana", "Orange"];

// Using the Array constructor


const numbers = new Array(1, 2, 3, 4);

Accessing Elements

Array elements are accessed using their index, starting from 0.

[Link](fruits[0]); // "Apple"
fruits[1] = "Mango"; // Modifying an element

Array Properties and Methods

Arrays come with many built-in properties and methods.

• length: Returns the number of elements. javascript


[Link]([Link]); // 3

Mutating Methods (Change the original array)

• push(): Adds elements to the end.


• pop(): Removes the last element.
• unshift(): Adds elements to the beginning.
• shift(): Removes the first element.
• splice(): Adds/removes elements at a specific index.

const arr = [1, 2, 3];


[Link](4); // [1, 2, 3, 4]
[Link](); // [1, 2, 3]
[Link](0); // [0, 1, 2, 3]
[Link](1, 1); // Removes 1 element at index 1 -> [0, 2, 3]

Non-Mutating Methods (Return a new array or value)

• concat(): Merges arrays.


• slice(): Extracts a portion of an array.
• indexOf(): Finds the index of an element.
• includes(): Checks if an element exists.

const arr1 = [1, 2];


const arr2 = [3, 4];
const combined = [Link](arr2); // [1, 2, 3, 4]
const part = [Link](1, 3); // [2, 3]

Iteration Methods (ES5/ES6)

• forEach(): Executes a function for each element.


• map(): Creates a new array with the results of calling a function for
every element.
• filter(): Creates a new array with elements that pass a test.
• reduce(): Reduces the array to a single value.

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

// map
const doubled = [Link](n => n * 2); // [2, 4, 6, 8]

// filter
const evens = [Link](n => n % 2 === 0); // [2, 4]
// reduce
const sum = [Link]((total, current) => total + current, 0); // 10

Interview Questions

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


2. How does the reduce() method work?
3. What is the difference between slice() and splice()?
4. How do you empty an array in JavaScript?

Multiple Choice Questions (MCQs)

1. Which method adds an element to the beginning of an array? a) push()


b) pop() c) shift() d) unshift() Answer: d) unshift()

2. Which method creates a new array with all elements that pass a test? a)
map() b) filter() c) reduce() d) forEach() Answer: b) filter()

© 2026 Manus AI. All rights reserved.

9. Strings
Strings are used for storing and manipulating text. A JavaScript string is zero or
more characters written inside quotes.
Creating Strings

Strings can be created using single quotes, double quotes, or backticks (template
literals).

let singleQuote = 'Hello World';


let doubleQuote = "Hello JavaScript";
let templateLiteral = `Hello ${singleQuote} and ${doubleQuote}!`;
[Link](templateLiteral); // Output: Hello Hello World and Hello JavaSc

String Properties and Methods

• length: Returns the length of the string. javascript let text =


"JavaScript"; [Link]([Link]); // 10

Common String Methods

• indexOf(): Returns the index of the first occurrence of a specified text.


• lastIndexOf(): Returns the index of the last occurrence.
• slice(start, end): Extracts a part of a string and returns a new string.
• substring(start, end): Similar to slice(), but cannot accept negative
indices.
• replace(search, replace): Replaces a specified value with another value
in a string.
• toUpperCase(): Converts a string to uppercase.
• toLowerCase(): Converts a string to lowercase.
• trim(): Removes whitespace from both ends of a string.
• split(separator): Splits a string into an array of substrings.

let sentence = "Hello, world! Welcome to JavaScript.";


[Link]([Link]("world")); // 7
[Link]([Link](7, 12)); // "world"
[Link]([Link]("world", "universe")); // "Hello, universe! We
[Link]([Link]()); // "HELLO, WORLD! WELCOME TO JAVASCRIP
[Link](" trim me ".trim()); // "trim me"
[Link]([Link](" ")); // ["Hello,", "world!", "Welcome", "to",

Template Literals (ES6)

Template literals (backticks `) offer enhanced functionality over traditional string


literals:

• Multi-line strings: Can span multiple lines without special characters.


• String interpolation: Embed expressions using ${expression}.

let firstName = "John";


let lastName = "Doe";
let fullName = `${firstName} ${lastName}`;

let multiLine = `This is a


multi-line
string.`;
[Link](multiLine);

Interview Questions

1. What is the difference between slice(), substring(), and substr()?


2. How do template literals improve string handling in JavaScript?
3. Explain the purpose of trim() and split() methods.

Multiple Choice Questions (MCQs)

1. Which character is used for template literals in JavaScript? a) " b) ' c) ` d) /


Answer: c) `

2. What will "JavaScript".slice(4, 7) return? a) "Scr" b) "ava" c) "aSc" d)


"vas" Answer: b) "ava"
10. Objects
In JavaScript, almost everything is an object. An object is a standalone entity, with
properties and types. Objects are collections of key-value pairs.

Creating Objects

Object Literal (Recommended)

const car = {
make: "Toyota",
model: "Camry",
year: 2020,
start: function() {
[Link]("Engine started!");
}
};

Using new Object()

const person = new Object();


[Link] = "Jane";
[Link] = "Doe";
[Link] = 28;

Accessing Object Properties

Properties can be accessed using dot notation or bracket notation.

[Link]([Link]); // "Toyota"
[Link](person["firstName"]); // "Jane"
// Dynamic property access
let prop = "model";
[Link](car[prop]); // "Camry"

Object Methods

An object method is an object property containing a function definition.

[Link](); // Output: Engine started!

this Keyword

The this keyword refers to the object it belongs to. In an object method, this
refers to the owner object.

const user = {
name: "Alice",
greet: function() {
[Link](`Hello, my name is ${[Link]}`);
}
};
[Link](); // Output: Hello, my name is Alice

Object Destructuring (ES6)

Allows you to unpack values from arrays, or properties from objects, into distinct
variables.

const book = { title: "The Hobbit", author: "J.R.R. Tolkien" };


const { title, author } = book;
[Link](title); // "The Hobbit"
[Link](author); // "J.R.R. Tolkien"

Interview Questions

1. What is an object in JavaScript?


2. Explain the difference between dot notation and bracket notation for
accessing object properties.
3. What is the role of the this keyword in JavaScript objects?
4. How does object destructuring work?

Multiple Choice Questions (MCQs)

1. Which of the following is the correct way to create an object literal? a) const
obj = new Object(); b) const obj = {}; c) const obj =
[Link](); d) const obj = []; Answer: b) const obj = {};

2. What will [Link]() output if user is defined as above? a) Hello, my


name is Alice b) Hello, my name is undefined c) Hello, my name
is [Link] d) Error Answer: a) Hello, my name is Alice

11. DOM Manipulation


The Document Object Model (DOM) is a programming interface for web
documents. It represents the page structure as a tree of objects, allowing programs
to change the document structure, style, and content.

Accessing HTML Elements

• [Link](id): Returns the element that has the ID


attribute with the specified value.
• [Link](name): Returns a collection of all
elements in the document with the specified class name.
• [Link](name): Returns a collection of all
elements with the specified tag name.
• [Link](selector): Returns the first element that
matches a specified CSS selector.
• [Link](selector): Returns a static NodeList
representing a list of the document's elements that match the specified group
of selectors.

<!-- [Link] -->


<div id="myDiv" class="container">
<p class="text">Hello DOM!</p>
</div>

const myDiv = [Link]("myDiv");


const paragraphs = [Link]("text");
const firstParagraph = [Link](".text");
const allParagraphs = [Link]("p");

[Link](myDiv); // <div id="myDiv" class="container">...</div>


[Link]([Link]); // "Hello DOM!"

Modifying HTML Elements

• [Link]: Gets or sets the HTML content of an element.


• [Link]: Gets or sets the text content of an element.
• [Link](attribute, value): Sets the value of an
attribute on the specified element.
• [Link]: Sets the inline style of an element.

[Link] = "<h2>New Content</h2>";


[Link] = "DOM Manipulated!";
[Link]("data-custom", "value");
[Link] = "lightblue";

Creating and Appending Elements

• [Link](tagName): Creates a new HTML element.


• [Link](childNode): Adds a new child node to an
element as the last child.
• [Link](newNode, referenceNode): Inserts a new
node before a reference node.

const newParagraph = [Link]("p");


[Link] = "This is a new paragraph.";
[Link](newParagraph);

Removing Elements

• [Link](childNode): Removes a child node from the


DOM.

[Link](newParagraph);

Interview Questions

1. What is the DOM, and why is it important?


2. Explain the difference between getElementById, querySelector, and
querySelectorAll.
3. How do you create a new HTML element using JavaScript and add it to the
page?
Multiple Choice Questions (MCQs)

1. Which method returns a collection of elements? a)


[Link]() b) [Link]() c)
[Link]() d) [Link]()
Answer: c) [Link]()

2. To change the text content of an element, which property would you use? a)
innerHTML b) textContent c) style d) attribute Answer: b)
textContent

12. Events
Events are actions or occurrences that happen in the system you are programming,
which the system tells you about so you can respond to them. Events are a core
part of interactive web development.

Common Event Types

• Mouse Events: click, mouseover, mouseout, mousedown, mouseup


• Keyboard Events: keydown, keyup, keypress
• Form Events: submit, change, focus, blur
• Document/Window Events: load, resize, scroll

Event Handlers

There are several ways to assign event handlers:

1. Inline Event Handlers (Discouraged)

<button onclick="alert('Button clicked!');">Click Me</button>


2. Traditional DOM Event Handlers

Assigning a function directly to an event property of an element.

const button = [Link]('button');


[Link] = function() {
[Link]('Button clicked!');
};

3. addEventListener() (Recommended)

The most flexible and powerful way to handle events. Allows multiple handlers for a
single event on an element.

const myButton = [Link]('myButton');

[Link]('click', function() {
[Link]('Button was clicked!');
});

[Link]('click', function() {
[Link]('Another action on click!');
});

// Removing an event listener


function doSomething() {
[Link]('Doing something...');
}
[Link]('mouseover', doSomething);
[Link]('mouseover', doSomething);
Event Object

When an event occurs, an event object is created and passed to the event handler
function. It contains information about the event.

[Link]('mousemove', function(event) {
[Link](`Mouse X: ${[Link]}, Mouse Y: ${[Link]}`);
});

Event Bubbling and Capturing

• Bubbling: Event propagates from the target element up to the document


(default).
• Capturing: Event propagates from the document down to the target element.

You can specify capturing by passing true as the third argument to


addEventListener.

[Link]() and
[Link]()

• [Link](): Stops the default action of an event (e.g., a form


submission, a link click).
• [Link](): Prevents the event from bubbling up or
capturing down the DOM tree.

[Link]('a').addEventListener('click', function(event) {
[Link](); // Prevents link from navigating
[Link]('Link click prevented!');
});
Interview Questions

1. What is an event in JavaScript?


2. Explain the difference between onclick and addEventListener.
3. What are event bubbling and event capturing?
4. When would you use [Link]() and
[Link]()?

Multiple Choice Questions (MCQs)

1. Which method is recommended for attaching event handlers in modern


JavaScript? a) Inline event handlers b) Traditional DOM event handlers c)
addEventListener() d) attachEvent() Answer: c) addEventListener()

2. What does [Link]() do? a) Stops event propagation. b)


Prevents the default action of the event. c) Stops the event from being fired.
d) None of the above. Answer: b) Prevents the default action of the event.

13. ES6 Features


ECMAScript 2015 (ES6) introduced a significant number of new features and
syntax improvements to JavaScript, making the language more powerful and easier
to write.

let and const

(Covered in Topic 2: Variables)

Arrow Functions

(Covered in Topic 7: Functions)

Template Literals

(Covered in Topic 9: Strings)


Destructuring Assignment

(Covered in Topic 10: Objects, also applies to Arrays)

// Array destructuring
const colors = ["red", "green", "blue"];
const [firstColor, secondColor] = colors;
[Link](firstColor); // "red"

Spread and Rest Operators (...)

Spread Operator

Expands an iterable (like an array or string) into individual elements.

• Copying arrays/objects: Creates a shallow copy.


• Concatenating arrays: Merges arrays.
• Passing arguments to functions: Spreads array elements as individual
arguments.

const arr1 = [1, 2];


const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]

const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }

function sum(x, y, z) { return x + y + z; }


const numbers = [1, 2, 3];
[Link](sum(...numbers)); // 6

Rest Parameter

Collects an indefinite number of arguments into an array.


function collectArgs(first, ...rest) {
[Link](first); // First argument
[Link](rest); // Array of remaining arguments
}
collectArgs(1, 2, 3, 4, 5); // first: 1, rest: [2, 3, 4, 5]

Classes

ES6 introduced JavaScript classes, which are syntactic sugar over JavaScript's
existing prototype-based inheritance. Classes provide a cleaner and more familiar
syntax for creating objects and handling inheritance.

class Person {
constructor(name, age) {
[Link] = name;
[Link] = age;
}

greet() {
[Link](`Hello, my name is ${[Link]} and I am ${[Link]} ye
}
}

const john = new Person("John", 30);


[Link](); // Output: Hello, my name is John and I am 30 years old.

Modules (Import/Export)

ES6 introduced a standardized module system, allowing developers to organize


code into separate files and import/export functionality.
// [Link]
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;

// [Link]
import { add, subtract } from './[Link]';
[Link](add(5, 3)); // 8

Interview Questions

1. List and explain at least five new features introduced in ES6.


2. What is the difference between the spread operator and the rest parameter?
3. How do ES6 classes work under the hood?
4. What are JavaScript modules, and why are they useful?

Multiple Choice Questions (MCQs)

1. Which ES6 feature allows you to unpack values from arrays or properties
from objects into distinct variables? a) Spread operator b) Rest parameter c)
Destructuring assignment d) Template literals Answer: c) Destructuring
assignment

2. What is the primary purpose of ES6 modules? a) To create new data types. b)
To enable server-side rendering. c) To organize and reuse code across files.
d) To improve browser compatibility. Answer: c) To organize and reuse code
across files.

14. Promises
Promises are a fundamental concept in modern JavaScript for handling
asynchronous operations. A Promise is an object representing the eventual
completion or failure of an asynchronous operation.
States of a Promise

A Promise can be in one of three states:

1. Pending: Initial state, neither fulfilled nor rejected.


2. Fulfilled (Resolved): The operation completed successfully.
3. Rejected: The operation failed.

Creating a Promise

A Promise is created using the Promise constructor, which takes a function (the
executor) with two arguments: resolve and reject.

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


// Simulate an asynchronous operation (e.g., fetching data)
setTimeout(() => {
const success = true;
if (success) {
resolve("Data fetched successfully!");
} else {
reject("Failed to fetch data.");
}
}, 2000);
});

Consuming a Promise

Promises are consumed using .then(), .catch(), and .finally() methods.

• .then(onFulfilled, onRejected): Handles a fulfilled Promise.


onFulfilled is called if the Promise resolves, onRejected if it rejects.
• .catch(onRejected): Handles only rejected Promises (a shorthand
for .then(null, onRejected)).
• .finally(onFinally): Executes a callback when the Promise is settled
(either fulfilled or rejected), regardless of the outcome.
myPromise
.then(message => {
[Link]("Success: " + message);
})
.catch(error => {
[Link]("Error: " + error);
})
.finally(() => {
[Link]("Promise settled.");
});

Chaining Promises

Promises can be chained together to perform a sequence of asynchronous


operations.

function fetchData(url) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (url === "[Link]") {
resolve({ data: "Some data from " + url });
} else {
reject("Failed to fetch from " + url);
}
}, 1000);
});
}

fetchData("[Link]")
.then(response => {
[Link]([Link]);
return fetchData("another_data.json"); // Chain another promise
})
.then(response => {
[Link]([Link]);
})
.catch(error => {
[Link]("Caught in chain: " + error);
});

[Link]() and [Link]()

• [Link]([promise1, promise2, ...]): Waits for all promises to


resolve, or for any one to reject. Returns an array of results.
• [Link]([promise1, promise2, ...]): Returns a promise that
resolves or rejects as soon as one of the promises in the iterable resolves or
rejects, with the value or reason from that promise.

Interview Questions

1. What is a Promise in JavaScript, and what are its three states?


2. How do you handle successful and failed Promise outcomes?
3. Explain Promise chaining with an example.
4. What is the difference between [Link]() and [Link]()?

Multiple Choice Questions (MCQs)

1. Which state indicates that a Promise operation completed successfully? a)


Pending b) Fulfilled c) Rejected d) Settled Answer: b) Fulfilled

2. Which method is used to handle errors in a Promise chain? a) .then()


b) .catch() c) .finally() d) .resolve() Answer: b) .catch()

15. Async/Await
async and await are ES2017 features that make asynchronous code look and
behave more like synchronous code, making it easier to read and write. They are
built on top of Promises.
async Function

An async function is a function declared with the async keyword. async functions
always return a Promise. If the function returns a non-Promise value, it will be
wrapped in a resolved Promise.

async function greeting() {


return "Hello, Async!";
}

greeting().then(message => [Link](message)); // Output: Hello, Async!

await Keyword

The await keyword can only be used inside an async function. It pauses the
execution of the async function until the Promise it's waiting for settles (resolves or
rejects).

function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}

async function asyncCall() {


[Link]('calling');
let result = await resolveAfter2Seconds();
[Link](result); // Output: 'resolved' after 2 seconds
[Link]('finished');
}
asyncCall();

Error Handling with Async/Await

Errors in async/await can be handled using try...catch blocks, similar to


synchronous code.

function rejectAfter1Second() {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject('Error: Something went wrong!');
}, 1000);
});
}

async function handleError() {


try {
let result = await rejectAfter1Second();
[Link](result);
} catch (error) {
[Link](error); // Output: Error: Something went wrong!
}
}

handleError();

Async/Await vs. Promises

async/await is essentially syntactic sugar over Promises. It provides a more


readable and maintainable way to work with asynchronous code, especially when
dealing with multiple sequential asynchronous operations.

Feature Promises (.then()/.catch()) Async/Await


Readability
Feature Promises (.then()/.catch()) Async/Await
Can become complex with deep More linear, synchronous-like
nesting (callback hell) flow
Error
.catch() method try...catch blocks
Handling
Harder to debug (stack traces can be Easier to debug (stack
Debugging
less clear) traces are clearer)

Interview Questions

1. What are async and await in JavaScript?


2. How do async/await improve asynchronous code readability?
3. How do you handle errors in async/await functions?
4. Can you use await outside an async function?

Multiple Choice Questions (MCQs)

1. An async function always returns a: a) Value b) Callback c) Promise d) Error


Answer: c) Promise

2. The await keyword can only be used inside: a) A regular function b) An


async function c) A global scope d) A try...catch block Answer: b) An
async function

16. Fetch API


The Fetch API provides a JavaScript interface for accessing and manipulating parts
of the HTTP pipeline, such as requests and responses. It offers a modern,
Promise-based alternative to XMLHttpRequest for making network requests.

Basic Fetch Request

The fetch() method takes one mandatory argument, the path to the resource you
want to fetch. It returns a Promise that resolves to the Response object.
fetch('[Link]
.then(response => {
if (![Link]) {
throw new Error(`HTTP error! status: ${[Link]}`);
}
return [Link](); // Parse the JSON body
})
.then(data => {
[Link](data);
})
.catch(error => {
[Link]('Fetch error:', error);
});

Handling Responses

The Response object returned by fetch() is a generic Response object, not the
actual JSON data. You need to call another method on the response (e.g.,
[Link](), [Link](), [Link]()) to extract the body
content.

• [Link](): Parses the response body as JSON.


• [Link](): Parses the response body as plain text.
• [Link](): Parses the response body as a Blob (for binary data).

Making POST Requests

To make a POST request, you need to pass a second argument to fetch() — an


options object. This object allows you to configure the request method, headers,
body, etc.

const postData = { name: 'John Doe', job: 'Developer' };

fetch('[Link] {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: [Link](postData),
})
.then(response => [Link]())
.then(data => {
[Link]('Success:', data);
})
.catch(error => {
[Link]('Error:', error);
});

Using Fetch with Async/Await

Combining fetch with async/await makes the code even cleaner.

async function fetchUsers() {


try {
const response = await fetch('[Link]
if (![Link]) {
throw new Error(`HTTP error! status: ${[Link]}`);
}
const users = await [Link]();
[Link](users);
} catch (error) {
[Link]('Could not fetch users:', error);
}
}

fetchUsers();
Interview Questions

1. What is the Fetch API, and how does it differ from XMLHttpRequest?
2. How do you make a GET request using fetch()?
3. How do you make a POST request with fetch() and send JSON data?
4. Explain how to handle errors when using fetch().

Multiple Choice Questions (MCQs)

1. The fetch() API returns a: a) Callback b) Promise c) XMLHttprequest object


d) JSON object Answer: b) Promise

2. To send JSON data in a POST request using fetch(), you should set the
Content-Type header to: a) text/plain b) application/x-www-form-
urlencoded c) application/json d) multipart/form-data Answer: c)
application/json

17. Error Handling


Error handling is a crucial aspect of robust JavaScript development. It allows your
programs to gracefully manage unexpected situations and prevent crashes.

try...catch Statement

The try...catch statement allows you to test a block of code for errors while it is
being executed, and handle the error if one occurs.

• The try block contains the code that might throw an error.
• The catch block contains the code to be executed if an error occurs in the
try block.
try {
// Code that may throw an error
let result = someUndefinedVariable * 10;
[Link](result);
} catch (error) {
// Code to handle the error
[Link]("An error occurred:", [Link]);
// Output: An error occurred: someUndefinedVariable is not defined
}

finally Block

The finally block executes code after try and catch blocks, regardless of the
outcome (whether an error occurred or not).

try {
[Link]("Inside try block.");
// throw new Error("Something went wrong!");
} catch (error) {
[Link]("Inside catch block:", [Link]);
} finally {
[Link]("Inside finally block. This always executes.");
}

throw Statement

The throw statement allows you to create custom errors. When an error is thrown,
the normal flow of the script is interrupted, and control is transferred to the nearest
catch block.

function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero is not allowed.");
}
return a / b;
}

try {
[Link](divide(10, 2)); // 5
[Link](divide(10, 0)); // Throws an error
} catch (error) {
[Link]("Caught an error:", [Link]);
// Output: Caught an error: Division by zero is not allowed.
}

Error Types

JavaScript has several built-in error types:

• Error: Generic error object.


• ReferenceError: Thrown when a non-existent variable is referenced.
• TypeError: Thrown when a value is not of the expected type.
• SyntaxError: Thrown when there is a syntax error in the code.
• RangeError: Thrown when a number is outside an allowable range.

Interview Questions

1. What is the purpose of try...catch...finally in JavaScript?


2. When would you use the throw statement?
3. Name a few common built-in error types in JavaScript.

Multiple Choice Questions (MCQs)

1. Which block of code is always executed, regardless of whether an error


occurred? a) try b) catch c) finally d) throw Answer: c) finally
2. What type of error is thrown when you try to use a variable that hasn't been
declared? a) TypeError b) SyntaxError c) ReferenceError d)
RangeError Answer: c) ReferenceError

18. Local Storage


Web storage (local storage and session storage) allows web applications to store
data locally within the user's browser. Unlike cookies, web storage has a much
larger capacity (typically 5MB to 10MB) and the data is not sent to the server with
every HTTP request.

Local Storage vs. Session Storage

Feature Local Storage Session Storage


Data Persists even after the browser is Cleared when the browser tab/
Persistence closed window is closed
Available across all tabs/windows Limited to the current tab/
Scope
from the same origin window
Capacity 5MB - 10MB 5MB - 10MB

Using Local Storage

The localStorage object provides methods to store, retrieve, and remove data.
Data is stored as key-value pairs, and both keys and values must be strings.

[Link](key, value)

Stores a key-value pair.

[Link]("username", "Alice");
[Link]("theme", "dark");
[Link](key)

Retrieves the value associated with a given key.

const username = [Link]("username");


[Link](username); // Output: Alice

[Link](key)

Removes a key-value pair.

[Link]("theme");

[Link]()

Removes all key-value pairs from local storage.

[Link]();

Storing Objects in Local Storage

Since local storage only stores strings, you need to convert objects to JSON strings
before storing them and parse them back when retrieving.

const userSettings = {
fontSize: "16px",
darkMode: true
};

// Store object
[Link]("settings", [Link](userSettings));

// Retrieve object
const storedSettings = [Link]([Link]("settings"));
[Link]([Link]); // Output: true

Interview Questions

1. What is local storage, and how does it differ from session storage?
2. How do you store and retrieve an object in local storage?
3. What are the limitations of local storage?

Multiple Choice Questions (MCQs)

1. Data stored in localStorage: a) Is sent with every HTTP request. b) Is


cleared when the browser tab is closed. c) Persists even after the browser is
closed. d) Has a capacity of only 4KB. Answer: c) Persists even after the
browser is closed.

2. To store an object in localStorage, you must first: a) Convert it to a


number. b) Convert it to a boolean. c) Convert it to a JSON string. d) Convert
it to an array. Answer: c) Convert it to a JSON string.

19. OOP in JavaScript


JavaScript is a multi-paradigm language, and while it doesn't have traditional class-
based inheritance like Java or C++, it supports Object-Oriented Programming
(OOP) through prototypes and, more recently, ES6 classes.

Prototypes

Every JavaScript object has a prototype. All JavaScript objects inherit properties
and methods from their prototype. The prototype chain is how JavaScript
implements inheritance.
function Animal(name) {
[Link] = name;
}

[Link] = function() {
[Link](`${[Link]} makes a sound.`);
};

const dog = new Animal("Dog");


[Link](); // Output: Dog makes a sound.

ES6 Classes

ES6 classes provide a cleaner and more familiar syntax for creating objects and
handling inheritance, but they are still syntactic sugar over JavaScript's existing
prototype-based inheritance.

Class Declaration

class Vehicle {
constructor(make, model) {
[Link] = make;
[Link] = model;
}

getDetails() {
return `${[Link]} ${[Link]}`;
}
}

const car = new Vehicle("Toyota", "Camry");


[Link]([Link]()); // Output: Toyota Camry
Inheritance with extends and super

Classes can inherit from other classes using the extends keyword. The super()
keyword is used to call the constructor of the parent class.

class Car extends Vehicle {


constructor(make, model, year) {
super(make, model); // Call parent constructor
[Link] = year;
}

getDetails() {
return `${[Link]()} (${[Link]})`;
}
}

const myCar = new Car("Honda", "Civic", 2022);


[Link]([Link]()); // Output: Honda Civic (2022)

Encapsulation

Encapsulation refers to bundling data (properties) and methods that operate on the
data within a single unit (object or class). JavaScript traditionally uses closures for
private members, but private class fields (#) are now a standard feature.

class BankAccount {
#balance = 0; // Private class field

constructor(initialBalance) {
if (initialBalance > 0) {
this.#balance = initialBalance;
}
}
deposit(amount) {
this.#balance += amount;
}

getBalance() {
return this.#balance;
}
}

const account = new BankAccount(100);


[Link](50);
[Link]([Link]()); // 150
// [Link](account.#balance); // SyntaxError: Private field '#balance'

Polymorphism

Polymorphism, meaning "many forms," allows objects of different classes to be


treated as objects of a common superclass. In JavaScript, this is often achieved
through method overriding or by simply having different objects respond to the
same method call in their own way.

class Shape {
draw() {
[Link]("Drawing a shape.");
}
}

class Circle extends Shape {


draw() {
[Link]("Drawing a circle.");
}
}

class Rectangle extends Shape {


draw() {
[Link]("Drawing a rectangle.");
}
}

const shapes = [new Circle(), new Rectangle()];


[Link](shape => [Link]());
// Output:
// Drawing a circle.
// Drawing a rectangle.

Interview Questions

1. How does JavaScript achieve OOP, given it's not a class-based language?
2. Explain prototypes and the prototype chain.
3. What are ES6 classes, and how do they relate to prototypes?
4. Describe encapsulation and polymorphism in JavaScript.

Multiple Choice Questions (MCQs)

1. ES6 classes in JavaScript are primarily: a) A new way to implement classical


inheritance. b) Syntactic sugar over prototype-based inheritance. c) A
replacement for functions. d) Used only for functional programming. Answer:
b) Syntactic sugar over prototype-based inheritance.

2. Which keyword is used to call the constructor of a parent class in an


inheriting class? a) this b) parent c) super d) extends Answer: c) super

20. Modules
JavaScript modules allow you to break up your code into separate files. This makes
your code more organized, maintainable, and reusable. ES6 introduced a native
module system (import/export).
Exporting Modules

Named Exports

You can export multiple values from a module by naming them.

// [Link]
export const add = (a, b) => a + b;
export function subtract(a, b) {
return a - b;
}

Default Exports

You can have only one default export per module. It's often used to export a single
class or function.

// [Link]
const PI = 3.14159;
export default PI;

// another_utils.js
export default class Calculator {
add(a, b) { return a + b; }
}

Importing Modules

Named Imports

// [Link]
import { add, subtract } from './[Link]';
[Link](add(10, 5)); // 15
[Link](subtract(10, 5)); // 5

Default Imports

When importing a default export, you can give it any name.

// [Link]
import myPI from './[Link]';
import MyCalculator from './another_utils.js';

[Link](myPI); // 3.14159
const calc = new MyCalculator();
[Link]([Link](2, 2)); // 4

Importing Everything

You can import all exports from a module as an object.

// [Link]
import * as MathFunctions from './[Link]';
[Link]([Link](2, 2)); // 4

Module Bundlers

While browsers now support ES modules, in complex applications, module bundlers


like Webpack, Rollup, or Parcel are often used. They combine multiple JavaScript
modules into a single file (or a few files) for deployment, optimizing for performance
and compatibility.

Interview Questions

1. What are JavaScript modules, and why are they important?


2. Explain the difference between named exports and default exports.
3. How do you import modules in JavaScript?
4. What is the role of module bundlers?

Multiple Choice Questions (MCQs)

1. How many default exports can a module have? a) Zero b) One c) Multiple d)
It depends on the bundler. Answer: b) One

2. Which keyword is used to import named exports? a) default b) from c)


import d) require Answer: c) import

21. Interview Questions (Comprehensive)


This section compiles a broader range of interview questions, covering fundamental
to advanced JavaScript concepts. It's designed to help solidify understanding and
prepare for technical interviews.

Fundamental Concepts

1. What is JavaScript, and what are its core features?


2. Explain event delegation.
3. What is closure in JavaScript? Provide an example.
4. Describe the event loop in JavaScript.
5. What is the difference between null and undefined?
6. What is the purpose of use strict?
7. Explain hoisting.
8. What is the difference between == and ===?
9. What are primitive and non-primitive data types?
10. How does prototypal inheritance work in JavaScript?

ES6+ Features

1. What are let, const, and var? Discuss their differences.


2. Explain arrow functions and their this binding.
3. What is destructuring assignment?
4. Differentiate between the spread operator and the rest parameter.
5. How do ES6 modules (import/export) work?
6. What are Promises, and how do you use them?
7. Explain async/await and its benefits.
8. What are JavaScript classes?

Web APIs and DOM

1. What is the DOM? How do you manipulate it?


2. Explain event bubbling and capturing.
3. How do you make an AJAX request? (Discuss XMLHttpRequest and Fetch
API)
4. What is local storage and session storage? What are their differences?
5. How can you prevent default browser behavior for an event?

Advanced Concepts

1. What is a higher-order function?


2. Explain call(), apply(), and bind() methods.
3. What is currying in JavaScript?
4. Describe the concept of memoization.
5. What is a generator function?
6. Explain debounce and throttle.
7. What is the difference between microtasks and macrotasks?

22. MCQs (Comprehensive)


This section provides a comprehensive set of multiple-choice questions to test your
knowledge across various JavaScript topics.

1. Which of the following is NOT a valid way to declare a variable in JavaScript?


a) var name; b) let name; c) const name; d) int name; Answer: d) int
name;

2. What is the output of [Link](typeof NaN);? a) "number" b) "string"


c) "undefined" d) "NaN" Answer: a) "number"
3. Which operator checks for both value and type equality? a) == b) != c) ===
d) !== Answer: c) ===

4. What will [1, 2, 3].map(num => num * 2) return? a) [1, 2, 3, 1, 2,


3] b) [2, 4, 6] c) [1, 2, 3] d) undefined Answer: b) [2, 4, 6]

5. Which method is used to add an element to the end of an array? a) shift()


b) unshift() c) push() d) pop() Answer: c) push()

6. What is the correct way to define an object method that refers to its own
properties? a) method: function() { [Link]([Link]); }
b) method: () => { [Link]([Link]); } c) method:
function() { [Link](property); } d) method: () =>
{ [Link]([Link]); } Answer: a) method: function()
{ [Link]([Link]); }

7. Which DOM method returns the first element that matches a specified CSS
selector? a) getElementById() b) getElementsByClassName() c)
querySelector() d) querySelectorAll() Answer: c) querySelector()

8. To prevent the default action of an event, you would use: a)


[Link]() b) [Link]() c)
[Link]() d) [Link] = true Answer: c)
[Link]()

9. Which ES6 feature allows you to combine multiple arguments into an array?
a) Spread operator b) Rest parameter c) Destructuring d) Template literals
Answer: b) Rest parameter

10. A Promise that has successfully completed is in which state? a) Pending b)


Fulfilled c) Rejected d) Settled Answer: b) Fulfilled

11. The await keyword can only be used inside a function declared with: a)
function b) async c) yield d) return Answer: b) async

12. Data stored in sessionStorage is cleared when: a) The browser is closed.


b) The browser tab/window is closed. c) The computer is restarted. d) The
user logs out. Answer: b) The browser tab/window is closed.
23. Mini Projects
Practical application of concepts is key to mastering JavaScript. Here are a few
mini-project ideas, ranging from basic to intermediate, to help you practice.

Project 1: Simple Calculator

Create a web-based calculator that can perform basic arithmetic operations


(addition, subtraction, multiplication, division).

Concepts to apply: * DOM Manipulation (getting input, displaying output) * Event


Handling (button clicks) * Operators * Conditional Statements

Project 2: To-Do List Application

Build a simple to-do list where users can add, delete, and mark tasks as complete.

Concepts to apply: * DOM Manipulation (creating, appending, removing elements) *


Event Handling (form submission, click events) * Arrays (storing tasks) * Local
Storage (persisting tasks)

Project 3: Image Carousel/Slider

Develop an image carousel that automatically cycles through images and allows
manual navigation with next/previous buttons.

Concepts to apply: * DOM Manipulation (changing image sources, visibility) * Event


Handling (button clicks, setTimeout/setInterval for auto-play) * Arrays (storing
image paths)

Project 4: Quiz Application

Create a multiple-choice quiz application with a timer, score tracking, and feedback
for correct/incorrect answers.

Concepts to apply: * DOM Manipulation * Event Handling * Arrays (storing


questions and answers) * Conditional Logic * Timers (setTimeout, setInterval)
24. Advanced JavaScript Concepts
This section delves into more advanced topics that are crucial for becoming a
proficient JavaScript developer.

Closures

A closure is the combination of a function bundled together (enclosed) with


references to its surrounding state (the lexical environment). In other words, a
closure gives you access to an outer function's scope from an inner function.

function makeCounter() {
let count = 0;
return function() {
return count++;
};
}

const counter = makeCounter();


[Link](counter()); // 0
[Link](counter()); // 1
[Link](counter()); // 2

Higher-Order Functions

A higher-order function is a function that takes one or more functions as


arguments, or returns a function as its result. Examples include map, filter,
reduce (covered in Arrays), and custom functions like debounce or throttle.

function operateOnArray(arr, operation) {


return [Link](operation);
}
const numbers = [1, 2, 3];
const doubled = operateOnArray(numbers, num => num * 2);
[Link](doubled); // [2, 4, 6]

Currying

Currying is a technique of transforming a function that takes multiple arguments into


a sequence of functions, each taking a single argument.

function curry(func) {
return function curried(...args) {
if ([Link] >= [Link]) {
return [Link](this, args);
} else {
return function(...args2) {
return [Link](this, [Link](args2));
};
}
};
}

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


const curriedAdd = curry(add);

[Link](curriedAdd(1)(2)(3)); // 6
[Link](curriedAdd(1, 2)(3)); // 6

Event Loop

The Event Loop is a fundamental concurrency model in JavaScript. It allows


JavaScript to perform non-blocking I/O operations despite being single-threaded. It
manages the execution of code, collects and processes events, and executes sub-
tasks from the queue.
Key Components: * Call Stack: Where synchronous code is executed. * Web APIs:
Provided by the browser (e.g., setTimeout, DOM events, fetch). * Callback
Queue (Task Queue): Where asynchronous tasks (like setTimeout callbacks,
DOM event handlers) are placed after Web APIs complete their work. * Event Loop:
Continuously monitors the Call Stack and the Callback Queue. If the Call Stack is
empty, it pushes the first function from the Callback Queue to the Call Stack.

Microtasks and Macrotasks

Within the event loop, there are two types of queues: the microtask queue and the
macrotask queue (also known as the task queue).

• Macrotasks (Tasks): setTimeout, setInterval, setImmediate, I/O, UI


rendering.
• Microtasks: Promise callbacks (.then(), .catch(), .finally()),
queueMicrotask, MutationObserver.

The event loop prioritizes microtasks. After each macrotask, all available microtasks
are executed before the next macrotask is processed.

[Link]("Script start");

setTimeout(() => {
[Link]("setTimeout");
}, 0);

[Link]()
.then(() => {
[Link]("Promise 1");
})
.then(() => {
[Link]("Promise 2");
});

[Link]("Script end");
// Expected Output:
// Script start
// Script end
// Promise 1
// Promise 2
// setTimeout

Web Workers

Web Workers provide a way to run scripts in background threads, separate from
the main execution thread of a web page. This allows for long-running scripts to be
executed without blocking the user interface.

// [Link]
[Link] = function(e) {
const result = [Link][0] * [Link][1];
[Link](result);
};

// [Link]
if ([Link]) {
const myWorker = new Worker("[Link]");

[Link]([10, 20]);

[Link] = function(e) {
[Link]("Message received from worker:", [Link]);
};
}

Conclusion

This handbook has covered a wide range of JavaScript topics, from the
fundamentals of variables and data types to advanced concepts like closures, the
event loop, and web workers. Mastering these concepts will provide a strong
foundation for building complex and efficient JavaScript applications. Continuous
learning and practice are key to becoming a proficient JavaScript developer.

17. Error Handling


Error handling is a crucial aspect of robust JavaScript development. It allows your
programs to gracefully manage unexpected situations and prevent crashes.

try...catch Statement

The try...catch statement allows you to test a block of code for errors while it is
being executed, and handle the error if one occurs.

• The try block contains the code that might throw an error.
• The catch block contains the code to be executed if an error occurs in the
try block.

try {
// Code that may throw an error
let result = someUndefinedVariable * 10;
[Link](result);
} catch (error) {
// Code to handle the error
[Link]("An error occurred:", [Link]);
// Output: An error occurred: someUndefinedVariable is not defined
}
finally Block

The finally block executes code after try and catch blocks, regardless of the
outcome (whether an error occurred or not).

try {
[Link]("Inside try block.");
// throw new Error("Something went wrong!");
} catch (error) {
[Link]("Inside catch block:", [Link]);
} finally {
[Link]("Inside finally block. This always executes.");
}

throw Statement

The throw statement allows you to create custom errors. When an error is thrown,
the normal flow of the script is interrupted, and control is transferred to the nearest
catch block.

function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero is not allowed.");
}
return a / b;
}

try {
[Link](divide(10, 2)); // 5
[Link](divide(10, 0)); // Throws an error
} catch (error) {
[Link]("Caught an error:", [Link]);
// Output: Caught an error: Division by zero is not allowed.
}

Error Types

JavaScript has several built-in error types:

• Error: Generic error object.


• ReferenceError: Thrown when a non-existent variable is referenced.
• TypeError: Thrown when a value is not of the expected type.
• SyntaxError: Thrown when there is a syntax error in the code.
• RangeError: Thrown when a number is outside an allowable range.

Interview Questions

1. What is the purpose of try...catch...finally in JavaScript?


2. When would you use the throw statement?
3. Name a few common built-in error types in JavaScript.

Multiple Choice Questions (MCQs)

1. Which block of code is always executed, regardless of whether an error


occurred? a) try b) catch c) finally d) throw Answer: c) finally

2. What type of error is thrown when you try to use a variable that hasn\\\\\\\\'t
been declared? a) TypeError b) SyntaxError c) ReferenceError d)
RangeError Answer: c) ReferenceError

18. Local Storage


Web storage (local storage and session storage) allows web applications to store
data locally within the user\\\\\\\\'s browser. Unlike cookies, web storage has a much
larger capacity (typically 5MB to 10MB) and the data is not sent to the server with
every HTTP request.
Local Storage vs. Session Storage

Feature Local Storage Session Storage


Data Persists even after the browser is Cleared when the browser tab/
Persistence closed window is closed
Available across all tabs/windows Limited to the current tab/
Scope
from the same origin window
Capacity 5MB - 10MB 5MB - 10MB

Using Local Storage

The localStorage object provides methods to store, retrieve, and remove data.
Data is stored as key-value pairs, and both keys and values must be strings.

[Link](key, value)

Stores a key-value pair.

[Link]("username", "Alice");
[Link]("theme", "dark");

[Link](key)

Retrieves the value associated with a given key.

const username = [Link]("username");


[Link](username); // Output: Alice

[Link](key)

Removes a key-value pair.


[Link]("theme");

[Link]()

Removes all key-value pairs from local storage.

[Link]();

Storing Objects in Local Storage

Since local storage only stores strings, you need to convert objects to JSON strings
before storing them and parse them back when retrieving.

const userSettings = {
fontSize: "16px",
darkMode: true
};

// Store object
[Link]("settings", [Link](userSettings));

// Retrieve object
const storedSettings = [Link]([Link]("settings"));
[Link]([Link]); // Output: true

Interview Questions

1. What is local storage, and how does it differ from session storage?
2. How do you store and retrieve an object in local storage?
3. What are the limitations of local storage?
Multiple Choice Questions (MCQs)

1. Data stored in localStorage: a) Is sent with every HTTP request. b) Is


cleared when the browser tab is closed. c) Persists even after the browser is
closed. d) Has a capacity of only 4KB. Answer: c) Persists even after the
browser is closed.

2. To store an object in localStorage, you must first: a) Convert it to a


number. b) Convert it to a boolean. c) Convert it to a JSON string. d) Convert
it to an array. Answer: c) Convert it to a JSON string.

19. OOP in JavaScript


JavaScript is a multi-paradigm language, and while it doesn\\\\\\\\\\\'t have traditional
class-based inheritance like Java or C++, it supports Object-Oriented Programming
(OOP) through prototypes and, more recently, ES6 classes.

Prototypes

Every JavaScript object has a prototype. All JavaScript objects inherit properties
and methods from their prototype. The prototype chain is how JavaScript
implements inheritance.

function Animal(name) {
[Link] = name;
}

[Link] = function() {
[Link](`${[Link]} makes a sound.`);
};

const dog = new Animal("Dog");


[Link](); // Output: Dog makes a sound.
ES6 Classes

ES6 classes provide a cleaner and more familiar syntax for creating objects and
handling inheritance, but they are still syntactic sugar over JavaScript\\\\\\\\\\\'s
existing prototype-based inheritance.

Class Declaration

class Vehicle {
constructor(make, model) {
[Link] = make;
[Link] = model;
}

getDetails() {
return `${[Link]} ${[Link]}`;
}
}

const car = new Vehicle("Toyota", "Camry");


[Link]([Link]()); // Output: Toyota Camry

Inheritance with extends and super

Classes can inherit from other classes using the extends keyword. The super()
keyword is used to call the constructor of the parent class.

class Car extends Vehicle {


constructor(make, model, year) {
super(make, model); // Call parent constructor
[Link] = year;
}

getDetails() {
return `${[Link]()} (${[Link]})`;
}
}

const myCar = new Car("Honda", "Civic", 2022);


[Link]([Link]()); // Output: Honda Civic (2022)

Encapsulation

Encapsulation refers to bundling data (properties) and methods that operate on the
data within a single unit (object or class). JavaScript traditionally uses closures for
private members, but private class fields (#) are now a standard feature.

class BankAccount {
#balance = 0; // Private class field

constructor(initialBalance) {
if (initialBalance > 0) {
this.#balance = initialBalance;
}
}

deposit(amount) {
this.#balance += amount;
}

getBalance() {
return this.#balance;
}
}

const account = new BankAccount(100);


[Link](50);
[Link]([Link]()); // 150
// [Link](account.#balance); // SyntaxError: Private field \\\\\\\\\\\

Polymorphism

Polymorphism, meaning "many forms," allows objects of different classes to be


treated as objects of a common superclass. In JavaScript, this is often achieved
through method overriding or by simply having different objects respond to the
same method call in their own way.

class Shape {
draw() {
[Link]("Drawing a shape.");
}
}

class Circle extends Shape {


draw() {
[Link]("Drawing a circle.");
}
}

class Rectangle extends Shape {


draw() {
[Link]("Drawing a rectangle.");
}
}

const shapes = [new Circle(), new Rectangle()];


[Link](shape => [Link]());
// Output:
// Drawing a circle.
// Drawing a rectangle.
Interview Questions

1. How does JavaScript achieve OOP, given it\\\\\\\\\\\'s not a class-based


language?
2. Explain prototypes and the prototype chain.
3. What are ES6 classes, and how do they relate to prototypes?
4. Describe encapsulation and polymorphism in JavaScript.

Multiple Choice Questions (MCQs)

1. ES6 classes in JavaScript are primarily: a) A new way to implement classical


inheritance. b) Syntactic sugar over prototype-based inheritance. c) A
replacement for functions. d) Used only for functional programming. Answer:
b) Syntactic sugar over prototype-based inheritance.

2. Which keyword is used to call the constructor of a parent class in an


inheriting class? a) this b) parent c) super d) extends Answer: c) super

20. Modules
JavaScript modules allow you to break up your code into separate files. This makes
your code more organized, maintainable, and reusable. ES6 introduced a native
module system (import/export).

Exporting Modules

Named Exports

You can export multiple values from a module by naming them.

// [Link]
export const add = (a, b) => a + b;
export function subtract(a, b) {
return a - b;
}

Default Exports

You can have only one default export per module. It\\\\\\\\\\\'s often used to export a
single class or function.

// [Link]
const PI = 3.14159;
export default PI;

// another_utils.js
export default class Calculator {
add(a, b) { return a + b; }
}

Importing Modules

Named Imports

// [Link]
import { add, subtract } from \\\\\\\\\\\\\\\\\\'./[Link]\\\\\\\\\\\\\\\\\

Default Imports

When importing a default export, you can give it any name.

// [Link]
import myPI from \\\\\\\\\\\\\\\\\\'./[Link]\\\\\\\\\\\\\\\\\'\nimport My
Importing Everything

You can import all exports from a module as an object.

// [Link]
import * as MathFunctions from \\\\\\\\\\\\\\\\\\'./[Link]\\\\\\\\\\\\\\\\

Module Bundlers

While browsers now support ES modules, in complex applications, module bundlers


like Webpack, Rollup, or Parcel are often used. They combine multiple JavaScript
modules into a single file (or a few files) for deployment, optimizing for performance
and compatibility.

Interview Questions

1. What are JavaScript modules, and why are they important?


2. Explain the difference between named exports and default exports.
3. How do you import modules in JavaScript?
4. What is the role of module bundlers?

Multiple Choice Questions (MCQs)

1. How many default exports can a module have? a) Zero b) One c) Multiple d)
It depends on the bundler. Answer: b) One

2. Which keyword is used to import named exports? a) default b) from c)


import d) require Answer: c) import

21. Interview Questions (Comprehensive)


This section compiles a broader range of interview questions, covering fundamental
to advanced JavaScript concepts. It\\\\\\\\\\\'s designed to help solidify understanding
and prepare for technical interviews.
Fundamental Concepts

1. What is JavaScript, and what are its core features?


2. Explain event delegation.
3. What is closure in JavaScript? Provide an example.
4. Describe the event loop in JavaScript.
5. What is the difference between null and undefined?
6. What is the purpose of use strict?
7. Explain hoisting.
8. What is the difference between == and ===?
9. What are primitive and non-primitive data types?
10. How does prototypal inheritance work in JavaScript?

ES6+ Features

1. What are let, const, and var? Discuss their differences.


2. Explain arrow functions and their this binding.
3. What is destructuring assignment?
4. Differentiate between the spread operator and the rest parameter.
5. How do ES6 modules (import/export) work?
6. What are Promises, and how do you use them?
7. Explain async/await and its benefits.
8. What are JavaScript classes?

Web APIs and DOM

1. What is the DOM? How do you manipulate it?


2. Explain event bubbling and capturing.
3. How do you make an AJAX request? (Discuss XMLHttpRequest and Fetch
API)
4. What is local storage and session storage? What are their differences?
5. How can you prevent default browser behavior for an event?

Advanced Concepts

1. What is a higher-order function?


2. Explain call(), apply(), and bind() methods.
3. What is currying in JavaScript?
4. Describe the concept of memoization.
5. What is a generator function?
6. Explain debounce and throttle.
7. What is the difference between microtasks and macrotasks?

22. MCQs (Comprehensive)


This section provides a comprehensive set of multiple-choice questions to test your
knowledge across various JavaScript topics.

1. Which of the following is NOT a valid way to declare a variable in JavaScript?


a) var name; b) let name; c) const name; d) int name; Answer: d) int
name;

2. What is the output of [Link](typeof NaN);? a) "number" b) "string"


c) "undefined" d) "NaN" Answer: a) "number"

3. Which operator checks for both value and type equality? a) == b) != c) ===
d) !== Answer: c) ===

4. What will [1, 2, 3].map(num => num * 2) return? a) [1, 2, 3, 1, 2,


3] b) [2, 4, 6] c) [1, 2, 3] d) undefined Answer: b) [2, 4, 6]

5. Which method is used to add an element to the end of an array? a) shift()


b) unshift() c) push() d) pop() Answer: c) push()

6. What is the correct way to define an object method that refers to its own
properties? a) method: function() { [Link]([Link]); }
b) method: () => { [Link]([Link]); } c) method:
function() { [Link](property); } d) method: () =>
{ [Link]([Link]); } Answer: a) method: function()
{ [Link]([Link]); }

7. Which DOM method returns the first element that matches a specified CSS
selector? a) getElementById() b) getElementsByClassName() c)
querySelector() d) querySelectorAll() Answer: c) querySelector()
8. To prevent the default action of an event, you would use: a)
[Link]() b) [Link]() c)
[Link]() d) [Link] = true Answer: c)
[Link]()

9. Which ES6 feature allows you to combine multiple arguments into an array?
a) Spread operator b) Rest parameter c) Destructuring d) Template literals
Answer: b) Rest parameter

10. A Promise that has successfully completed is in which state? a) Pending b)


Fulfilled c) Rejected d) Settled Answer: b) Fulfilled

11. The await keyword can only be used inside a function declared with: a)
function b) async c) yield d) return Answer: b) async

12. Data stored in sessionStorage is cleared when: a) The browser is closed.


b) The browser tab/window is closed. c) The computer is restarted. d) The
user logs out. Answer: b) The browser tab/window is closed.

23. Mini Projects


Practical application of concepts is key to mastering JavaScript. Here are a few
mini-project ideas, ranging from basic to intermediate, to help you practice.

Project 1: Simple Calculator

Create a web-based calculator that can perform basic arithmetic operations


(addition, subtraction, multiplication, division).

Concepts to apply:

• DOM Manipulation (getting input, displaying output)


• Event Handling (button clicks)
• Operators
• Conditional Statements
Project 2: To-Do List Application

Build a simple to-do list where users can add, delete, and mark tasks as complete.

Concepts to apply:

• DOM Manipulation (creating, appending, removing elements)


• Event Handling (form submission, click events)
• Arrays (storing tasks)
• Local Storage (persisting tasks)

Project 3: Image Carousel/Slider

Develop an image carousel that automatically cycles through images and allows
manual navigation with next/previous buttons.

Concepts to apply:

• DOM Manipulation (changing image sources, visibility)


• Event Handling (button clicks, setTimeout/setInterval for auto-play)
• Arrays (storing image paths)

Project 4: Quiz Application

Create a multiple-choice quiz application with a timer, score tracking, and feedback
for correct/incorrect answers.

Concepts to apply:

• DOM Manipulation
• Event Handling
• Arrays (storing questions and answers)
• Conditional Logic
• Timers (setTimeout, setInterval)
24. Advanced JavaScript Concepts
This section delves into more advanced topics that are crucial for becoming a
proficient JavaScript developer.

Closures

A closure is the combination of a function bundled together (enclosed) with


references to its surrounding state (the lexical environment). In other words, a
closure gives you access to an outer function\\\\\\\\\\\'s scope from an inner function.

function makeCounter() {
let count = 0;
return function() {
return count++;
};
}

const counter = makeCounter();


[Link](counter()); // 0
[Link](counter()); // 1
[Link](counter()); // 2

Higher-Order Functions

A higher-order function is a function that takes one or more functions as


arguments, or returns a function as its result. Examples include map, filter,
reduce (covered in Arrays), and custom functions like debounce or throttle.

function operateOnArray(arr, operation) {


return [Link](operation);
}
const numbers = [1, 2, 3];
const doubled = operateOnArray(numbers, num => num * 2);
[Link](doubled); // [2, 4, 6]

Currying

Currying is a technique of transforming a function that takes multiple arguments into


a sequence of functions, each taking a single argument.

function curry(func) {
return function curried(...args) {
if ([Link] >= [Link]) {
return [Link](this, args);
} else {
return function(...args2) {
return [Link](this, [Link](args2));
};
}
};
}

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


const curriedAdd = curry(add);

[Link](curriedAdd(1)(2)(3)); // 6
[Link](curriedAdd(1, 2)(3)); // 6

Event Loop

The Event Loop is a fundamental concurrency model in JavaScript. It allows


JavaScript to perform non-blocking I/O operations despite being single-threaded. It
manages the execution of code, collects and processes events, and executes sub-
tasks from the queue.
Key Components:

• Call Stack: Where synchronous code is executed.


• Web APIs: Provided by the browser (e.g., setTimeout, DOM events, fetch).
• Callback Queue (Task Queue): Where asynchronous tasks (like setTimeout
callbacks, DOM event handlers) are placed after Web APIs complete their
work.
• Event Loop: Continuously monitors the Call Stack and the Callback Queue. If
the Call Stack is empty, it pushes the first function from the Callback Queue
to the Call Stack.

Microtasks and Macrotasks

Within the event loop, there are two types of queues: the microtask queue and the
macrotask queue (also known as the task queue).

• Macrotasks (Tasks): setTimeout, setInterval, setImmediate, I/O, UI


rendering.
• Microtasks: Promise callbacks (.then(), .catch(), .finally()),
queueMicrotask, MutationObserver.

The event loop prioritizes microtasks. After each macrotask, all available microtasks
are executed before the next macrotask is processed.

[Link]("Script start");

setTimeout(() => {
[Link]("setTimeout");
}, 0);

[Link]()
.then(() => {
[Link]("Promise 1");
})
.then(() => {
[Link]("Promise 2");
});
[Link]("Script end");

// Expected Output:
// Script start
// Script end
// Promise 1
// Promise 2
// setTimeout

Web Workers

Web Workers provide a way to run scripts in background threads, separate from
the main execution thread of a web page. This allows for long-running scripts to be
executed without blocking the user interface.

// [Link]
[Link] = function(e) {
const result = [Link][0] * [Link][1];
[Link](result);
};

// [Link]
if ([Link]) {
const myWorker = new Worker("[Link]");

[Link]([10, 20]);

[Link] = function(e) {
[Link]("Message received from worker:", [Link]);
};
}
Conclusion

This handbook has covered a wide range of JavaScript topics, from the
fundamentals of variables and data types to advanced concepts like closures, the
event loop, and web workers. Mastering these concepts will provide a strong
foundation for building complex and efficient JavaScript applications. Continuous
learning and practice are key to becoming a proficient JavaScript developer.

You might also like