0% found this document useful (0 votes)
27 views252 pages

JavaScript HandBook

Uploaded by

kalebmekonen.kb
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)
27 views252 pages

JavaScript HandBook

Uploaded by

kalebmekonen.kb
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
You are on page 1/ 252

JavaScript HandBook

by : Muhammed Teshome

Learn with us :
Telegram: https://t.me/EmmersiveLearning

Youtube: https://www.youtube.com/@EmmersiveLearning/
JavaScript Course Outline
Here’s an outline for a comprehensive JavaScript course that covers everything
from the basics to advanced topics:

Module 1: Introduction to JavaScript

ng
1. Overview of JavaScript

ni
○ What is JavaScript?
○ History and Evolution

ar
○ How JavaScript Works in the Browser
○ JavaScript in Modern Web Development
2. Setting Up the Environment Le
○ Text Editors (VS Code, Sublime, etc.)
○ Introduction to the Browser Console
ve

○ Writing and Running Your First JavaScript Program


si

Module 2: JavaScript Basics


er

1. Syntax and Fundamentals


○ Variables and Data Types (Strings, Numbers, Booleans, Undefined,
m

Null)
Em

○ Operators (Arithmetic, Comparison, Logical, Assignment)


○ Comments and Code Structure
2. Control Structures
○ Conditional Statements (if, else, switch)
○ Loops (for, while, do...while)
○ Break and Continue Statements
3. Functions

1
○ Defining and Calling Functions
○ Function Parameters and Return Values
○ Function Expressions and Arrow Functions
○ Scope and Closures

Module 3: Working with Data

ng
1. Arrays
○ Creating and Accessing Arrays

ni
○ Array Methods (push, pop, shift, unshift, map, filter, reduce, etc.)
○ Iterating through Arrays

ar
2. Objects
○ Creating and Accessing Objects
Le
○ Object Methods and this Keyword
○ Object Iteration (for...in, Object.keys, etc.)
ve
○ Nested Objects and Arrays
3. Working with Strings
si

○ String Methods (substring, slice, replace, etc.)


○ Template Literals
er

○ String Interpolation
m

Module 4: Advanced JavaScript Concepts


Em

1. ES6+ Features
○ let, const, and Block Scoping
○ Template Strings
○ Arrow Functions
○ Destructuring Arrays and Objects
○ Spread and Rest Operators
○ Default Parameters

2
○ Promises and Async/Await
○ Modules (import/export)
2. Object-Oriented JavaScript
○ Introduction to Object-Oriented Programming (OOP)
○ Constructor Functions
○ Prototypes and Inheritance

ng
○ Classes and extends keyword
○ Encapsulation, Inheritance, and Polymorphism

ni
Module 5: DOM Manipulation

ar
1. Introduction to the DOM
○ Understanding the Document Object Model (DOM)
Le
○ Selecting DOM Elements (getElementById, querySelector, etc.)
○ Modifying DOM Elements (textContent, innerHTML, etc.)
ve
○ Adding and Removing Elements
2. Event Handling
si

○ Event Listeners (click, input, etc.)


○ Event Object and Event Delegation
er

○ Form Handling and Validation


○ Bubbling and Capturing
m

Module 6: Asynchronous JavaScript


Em

1. Callbacks
○ Introduction to Callbacks
○ Callback Functions and Error Handling
2. Promises
○ What are Promises?
○ Creating and Using Promises

3
○ Chaining Promises
○ Error Handling with Promises
3. Async/Await
○ Understanding Async Functions
○ Error Handling in Async/Await
○ Combining Async/Await with Promises

ng
4. Working with APIs
○ Introduction to REST APIs
○ Making HTTP Requests (Fetch API, Axios)

ni
○ Handling Responses and Errors

ar
○ Working with JSON

Module 7: JavaScript in the Browser

1. Browser APIs
Le
○ Introduction to Browser APIs
ve

○ Working with the window Object


si

○ LocalStorage and SessionStorage


○ Geolocation API
er

○ Fetch API for AJAX Requests


2. JavaScript and the User Interface
m

○ Introduction to Event Loop and Asynchronous Code


Em

○ Creating Interactive Forms


○ DOM Events and User Interaction
○ Animations with JavaScript and CSS

Module 8: JavaScript and Web Development

1. Integrating JavaScript with HTML/CSS


○ Understanding How JavaScript Works with HTML and CSS

4
○ Adding Interactivity to a Web Page
○ JavaScript Frameworks and Libraries (Overview of React, Vue,
Angular)
2. JavaScript Build Tools
○ Introduction to NPM
○ Introduction to Webpack

ng
○ Babel for JavaScript Compatibility
○ Task Runners (Gulp)

ni
Module 9: Testing and Debugging

ar
1. Debugging JavaScript
○ Common JavaScript Errors and How to Fix Them
Le
○ Using Browser Developer Tools for Debugging
○ Breakpoints and Watch Expressions
2. Testing JavaScript
ve

○ Introduction to Unit Testing


○ Testing Frameworks (Jest, Mocha, Jasmine)
si

○ Writing Simple Tests


er

○ Test-Driven Development (TDD)


m

Module 10: Advanced Topics and Best Practices


Em

1. Performance Optimization
○ Understanding the JavaScript Execution Context
○ Best Practices for Writing Efficient Code
○ Memory Management and Garbage Collection
2. Security Considerations
○ Introduction to JavaScript Security
○ Preventing Cross-Site Scripting (XSS) Attacks

5
○ Content Security Policy (CSP)
3. JavaScript Patterns
○ Introduction to Design Patterns
○ Module Pattern, Revealing Module Pattern
○ Observer Pattern, Singleton Pattern, etc.
4. JavaScript Best Practices

ng
○ Writing Clean and Maintainable Code
○ Following JavaScript Style Guides
○ Version Control with Git

ni
Module 11: JavaScript Project

ar
1. Project 1: To-Do List App
○ Overview and Project Setup
○ Building the User Interface
Le
○ Adding Functionality (Add, Edit, Delete Tasks)
ve

○ Persisting Data with LocalStorage


2. Project 2: Weather App
si

○ Integrating a Weather API


er

○ Fetching and Displaying Weather Data


○ Error Handling and User Input Validation
m

3. Project 3: Interactive Quiz App


○ Creating the Quiz Interface
Em

○ Handling User Input and Scoring


○ Using JavaScript for Dynamic Content Loading

6
2. JavaScript Intro
What is js?

ng
ni
ar
Le
JavaScript is one of the core technologies of the web, alongside HTML and CSS.
It's a programming language that enables interactive web pages and is an
ve

essential part of web applications. If you've ever interacted with a web


page—clicked a button, filled out a form, or played a video—JavaScript was likely
si

behind the scenes making it all work.


er
m
Em

7
1. What is JavaScript?

JavaScript is a high-level, interpreted programming language. It is a


multi-paradigm language, meaning it supports object-oriented, procedural, and
functional programming styles. JavaScript is primarily used to enhance web
pages, making them more dynamic and interactive.

ng
ni
ar
Le
ve
si

2. The History and Evolution of JavaScript


er

● 1995: JavaScript was created by Brendan Eich while working at Netscape.


m

Initially, it was called "Mocha," then "LiveScript," and finally "JavaScript" to


capitalize on the popularity of Java at the time.
Em

● 1997: JavaScript was standardized under the name ECMAScript by the


European Computer Manufacturers Association (ECMA).
● 2009: Node.js was released, allowing JavaScript to be used on the
server-side.
● 2015: ECMAScript 6 (ES6) was released, introducing significant language
improvements like classes, modules, arrow functions, and more.

8
ng
ni
ar
JavaScript has continued to evolve, becoming one of the most popular
programming languages in the world. Le
3. How JavaScript Works in the Browser
ve

When you write JavaScript code, it is executed by the browser's JavaScript


engine. Every major browser has a built-in JavaScript engine:
si

● Google Chrome: V8
er

● Mozilla Firefox: SpiderMonkey


● Safari: JavaScriptCore
m

● Microsoft Edge: Chakra (for the legacy Edge) and V8 (for the
Em

Chromium-based Edge)

These engines parse your code, convert it into machine code, and execute it,
allowing your web page to respond to user interactions in real-time.

9
ng
ni
ar
Le
4. JavaScript in Modern Web Development

JavaScript is used for a wide range of tasks in modern web development,


ve
including:

● Creating interactive user interfaces with frameworks like React, Angular,


si

and Vue.js.
er

● Building server-side applications with Node.js.


● Handling asynchronous operations such as fetching data from APIs.
m

● Developing mobile apps using frameworks like React Native.


● Building desktop applications using Electron.
Em

10
ng
ni
ar
Le
JavaScript's versatility makes it an invaluable tool for web developers, enabling
them to create complex applications that work seamlessly across different
platforms.
ve

5. Setting Up Your Environment


si

Before you start coding in JavaScript, you need to set up your environment:
er

1. Text Editors: You can write JavaScript code in any text editor, but some
m

popular ones include:


○ Visual Studio Code: A free, open-source code editor with built-in
Em

support for JavaScript.


○ Sublime Text: A lightweight and fast text editor with various plugins
available.
○ Atom: Another open-source editor, developed by GitHub, with strong
community support.
2. The Browser Console: Every modern browser has a JavaScript console
where you can write and test JavaScript code.

11
○ Accessing the Console:
■ In Chrome or Firefox: Right-click on a web page, select
"Inspect," and go to the "Console" tab.
■ In Safari: Enable the "Develop" menu in Preferences, then
select "Show JavaScript Console" from the Develop menu.
○ Writing Code in the Console: You can type JavaScript directly into

ng
the console and press Enter to see the results.
3. Writing Your First JavaScript Program

ni
○ Open your text editor.
○ Create a new file called index.html.

ar
○ Add the following HTML structure:

Code :

<!DOCTYPE html>
Le
<html lang="en">
ve
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
si

initial-scale=1.0">
<title>My First JavaScript Program</title>
er

</head>
<body>
m

<h1>Hello, World!</h1>
<script>
Em

console.log("Hello, World!");
</script>
</body>
</html>

4.
○ Save the file and open it in your web browser.

12
○ Open the browser console (as described above), and you should
see "Hello, World!" printed in the console.

This simple program demonstrates how JavaScript can be embedded in an


HTML document to produce output in the browser's console.

ng
This introduction provides a foundational understanding of what JavaScript is,
how it works, and how it fits into modern web development. From here, you can

ni
start exploring the syntax and basics of the language.

ar
2. JavaScript Variables and Data
Le
Types
ve
si

JS Variables
er

Variables in JavaScript are used to store data that can be used and manipulated
m

later in your program. Understanding variables and data types is fundamental to


writing effective JavaScript code.
Em

1. What is a Variable?

A variable is a container that holds data values. You can think of it as a named
storage location in memory where you can store and retrieve data.

13
ng
ni
2. Declaring Variables

ar
In JavaScript, you can declare variables using three keywords: var, let, and
const.
Le
ve
si
er
m

● var: The traditional way to declare a variable. It's function-scoped,


meaning it is accessible within the function it's declared in.
Em

● let: Introduced in ES6 (ES2015), let is block-scoped, meaning it's only


accessible within the block {} in which it's declared. It's the preferred way
to declare variables when you expect the value to change.
● const: Also introduced in ES6, const is used to declare
constants—variables that are block-scoped and cannot be reassigned after

14
they are initialized. However, if the constant is an object or array, the
properties or elements can be modified.

Example:

var myVar = 10; // Function-scoped


let myLet = 20; // Block-scoped

ng
const myConst = 30; // Block-scoped and immutable

ni
ar
Le
ve
si
er

3. Variable Naming Rules


m

● Variables must begin with a letter, underscore (_), or dollar sign ($).
Em

● They cannot start with a number.


● Variable names are case-sensitive (myVar and myvar are different).
● Use descriptive names to make your code easier to understand.

Example:

15
let firstName = "John"; // Correct
let _age = 25; // Correct
let $amount = 100.50; // Correct
let 2ndPlace = "Silver"; // Incorrect (cannot

ng
JS Data Types

ni
4. What are JavaScript Data Types

ar
JavaScript has several data types that fall into two categories: primitive and
non-primitive.
Le
ve
si
er
m
Em

Primitive Data Types

1. Number: Represents both integers and floating-point numbers.


○ Example: let age = 25;, let price = 99.99;
2. String: Represents a sequence of characters (text).

16
○ Example: let name = "Emmersive";, let greeting =
'Hello, world!';
3. Boolean: Represents a logical value: either true or false.
○ Example: let isOnline = true;, let isLoggedIn =
false;
4. Undefined: A variable that has been declared but not assigned a value is

ng
undefined.
○ Example

ni
ar
let city;
console.log(city); // Output: undefined

Le
5. Null: Represents the intentional absence of any object value. It's often
used to signify that a variable is empty or unknown.
ve
○ Example: let user = null;
6. Symbol: A unique and immutable primitive value, introduced in ES6, often
si

used as a key for object properties.


○ Example: let sym = Symbol("unique");
er

7. BigInt: Represents integers with arbitrary precision, introduced in ES2020.


It's used for numbers larger than the safe integer limit for regular numbers.
m

○ Example: let bigNumber =


Em

123456789012345678901234567890n;

Non-Primitive Data Types

1. Object: Used to store collections of data and more complex entities.


○ Example:

Javascript Code

17
let person = {
firstName: "Mehammed",
lastName: "Teshome",
age: 30
};

ng
2. Array: A special type of object used to store multiple values in a single
variable.
○ Example:

ni
Javascript Code

ar
let colors = ["red", "green", "blue"];

5. Type Checking
Le
To check the type of a variable in JavaScript, you can use the typeof operator.
ve

Example:
si

javascript code
er

let age = 27;


let name = "Mehammed";
m

let isOnline = true;


Em

console.log(typeof age); // Output: "number"


console.log(typeof name); // Output: "string"
console.log(typeof isOnline); // Output: "boolean"

18
6. Type Conversion

JavaScript is a dynamically typed language, meaning variables can change


types. You can convert between data types using various methods.

● String Conversion: Convert a number or other types to a string.


○ Example: let numToStr = String(123); // "123"

ng
● Number Conversion: Convert a string or other types to a number.
○ Example: let strToNum = Number("123"); // 123

ni
● Boolean Conversion: Convert a string, number, or other types to a
boolean.

ar
○ Example:

let numToBool = Boolean(0);


Le
let strToBool = Boolean("Hello"); // true
// false
ve

7. Mutable vs Immutable
si

Primitive Data Types are immutable, meaning their values cannot be changed.
er

When you reassign a variable with a primitive value, you're not changing the
existing value; you're creating a new one.
m

Example:
Em

let greeting = "Hello";


greeting = "Hi"; // "Hello" is replaced with "Hi"

Non-Primitive Data Types (like objects and arrays) are mutable, meaning their
values can be changed without reassigning the variable.
Example:

19
let person = { name: "John" };
person.name = "Jane"; // The name property is changed to "Jane"

By understanding variables and data types, you now have the foundation to start
writing more complex and dynamic JavaScript programs. This knowledge will

ng
help you manage and manipulate data effectively as you continue to learn more
about JavaScript.

ni
ar
Le
3. JavaScript Expressions and Statements
ve
si

In JavaScript, understanding the difference between expressions and statements


er

and Operators is fundamental for writing and comprehending code. All are
building blocks of the language, but they serve different purposes.
m

1. JavaScript Expressions
Em

An expression is a piece of code that evaluates to a value. This value can be of


any data type, such as a number, string, boolean, or even an object.

1.1 Types of Expressions

1. Literal Expressions:

20
○ These are the simplest forms of expressions that directly represent
values.

Example:
Javascript code

42; // A number literal


"Hello, world!"; // A string literal

ng
true; // A boolean literal

ni
2. Variable Expressions:

ar
○ A variable expression is just a variable, which itself evaluates to the
value stored in the variable.

Example:
Le
Javascript code
ve

let x = 5;
si

x; // This expression evaluates to 5


er

3. Operator Expressions:
m

○ These are combinations of variables, literals, and operators that


Em

evaluate to a single value.

Example:
Javascript code

let sum = 2 + 3; // The expression 2 + 3 evaluates to 5


let product = sum * 2; // The expression sum * 2 evaluates to 10

21

4. Function Expressions:
○ A function can be an expression, especially when the function is
assigned to a variable.

Example:
Javascript code

ng
let square = function(x) {

ni
return x * x;

ar
};
square(4); // This expression evaluates to 16
Le
5. Object and Array Expressions:
ve
○ Creating objects and arrays can also be expressions.

Example:
si

Javascript code
er
m

let person = { name: "Alice", age: 25 }; // Object expression


let numbers = [1, 2, 3, 4]; // Array expression
Em

6. Logical Expressions:
○ These expressions use logical operators and evaluate to a boolean
value.

22
Example:

let isAdult = age > 18; // Evaluates to true or false


let canVote = isCitizen && isAdult; // Evaluates to true or
false

ng

1.2 Examples of Expressions in Context

ni
Example:

ar
let a = 10;
let b = 20; Le
let c = a + b; // The expression a + b evaluates to 30 and is
assigned to c
ve

● Here, a + b is an expression that evaluates to 30, and the whole line let
si

c = a + b; is a statement.
er

2. JavaScript Statements
m

A statement is a unit of code that performs an action. Statements are often


Em

composed of expressions but serve to control the flow of the program.

2.1 Types of Statements

1. Declaration Statements:
○ These statements are used to declare variables or constants.

23
Example:

let x = 5;
const PI = 3.14159;

ng
2. Assignment Statements:
○ These statements assign a value to a variable.

ni
Example:

ar
x = 10;
name = "John"; Le

ve
3. Control Flow Statements:
○ These statements control the execution flow of the program.
si

○ Examples:
er

Conditional Statements:
m

if (x > 10) {
Em

console.log("x is greater than 10");


} else {
console.log("x is 10 or less");
}

24
Loops:

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


console.log(i);
}

ng
4. Function Declaration:

ni
○ This statement defines a function.

ar
Example:

function greet() {
Le
console.log("Hello, world!");
ve
}
si


5. Return Statement:
er

○ The return statement is used to exit a function and return a value.


m

Example:
Em

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


6. Expression Statements:
○ Sometimes, an expression can be a statement if it stands alone and
its value is not used.

25
Example:

x + y; // This is an expression statement; its value is computed


but not used

7. Block Statements:

ng
○ A block statement groups zero or more statements inside curly
braces {}.

ni
Example:

ar
{
let a = 1;
let b = 2;
Le
console.log(a + b); // Output: 3
ve

}
si
er

2.2 Examples of Statements in Context


Example:
m
Em

let age = 18; // Declaration and assignment statement

if (age >= 18) {


console.log("You are an adult."); // This is a statement
inside the if block
}

26
● Here, let age = 18; is a declaration and assignment statement. The
if block contains a control flow statement, and inside the block, there is a
console.log statement.

3. Expressions vs. Statements

● Expression: Produces a value.

ng
○ Example: 3 + 4, "Hello, " + "world!", x * y
● Statement: Performs an action and does not necessarily produce a value.

ni
○ Example:
let x = 5;, if (x > 0) { console.log(x); }, while (x <

ar
10) { x++; }

Example: Le
let a = 10; // Statement (declaration and assignment)
ve
let b = 20; // Statement (declaration and assignment)
si

let sum = a + b; // a + b is an expression, and the entire line


is a statement
er

if (sum > 25) { // if statement (control flow)


m

console.log("Sum is greater than 25"); // Statement (function


Em

call)
}

In summary, expressions in JavaScript produce values, while statements perform


actions that can involve expressions. Understanding the difference between
these two is key to mastering JavaScript programming.

27
JavaScript Operators

Look the image below.

ng
ni
ar
Le
ve
si

JavaScript operators are special symbols or keywords that are used to perform
er

operations on values or variables. Understanding operators is essential for


m

manipulating data, controlling the flow of your code, and implementing logic in
your programs.
Em

Types of Operators

28
ng
ni
ar
Le
There are about 8 types of operators in javaScript.
ve
si
er
m
Em

1. Arithmetic Operators

Arithmetic operators are used to perform basic mathematical operations like


addition, subtraction, multiplication, etc.

29
ng
ni
ar
Le
Addition (+): Adds two numbers or concatenates two strings.
Example :
ve
si

let sum = 10 + 5; // 15
let greeting = "Hello, " + "World!"; // "Hello, World!"
er

Subtraction (-): Subtracts the right operand from the left operand.
m
Em

let difference = 10 - 5; // 5

Multiplication (*): Multiplies two numbers.

30
let product = 10 * 5; // 50

Division (/): Divides the left operand by the right operand.

let quotient = 10 / 2; // 5

Modulus (%): Returns the remainder of the division of two numbers.

ng
let remainder = 10 % 3; // 1

ni
Exponentiation (**): Raises the first operand to the power of the second

ar
operand.

let power = 2 ** 3; // 8
Le

ve

Increment (++): Increases the value of a variable by 1.


si
er

let a = 5;
a++; // a is now 6
m


Em

Decrement (--): Decreases the value of a variable by 1.

let b = 5;
b--; // b is now 4

31
2. Assignment Operators

Assignment operators are used to assign values to variables.

ng
ni
ar
Le
ve
si
er
m
Em

Assignment (=): Assigns the value of the right operand to the left operand.
javascript
Copy code
let x = 10;

32
Addition Assignment (+=): Adds the right operand to the left operand and
assigns the result to the left operand.

let x = 10;
x += 5; // x is now 15

ng
Subtraction Assignment (-=): Subtracts the right operand from the left operand

ni
and assigns the result to the left operand.

ar
let x = 10;
x -= 5; // x is now 5 Le

ve

Multiplication Assignment (*=): Multiplies the left operand by the right operand
and assigns the result to the left operand.
si
er

let x = 10;
m

x *= 2; // x is now 20
Em

Division Assignment (/=): Divides the left operand by the right operand and
assigns the result to the left operand.

let x = 10;
x /= 2; // x is now 5

33

Modulus Assignment (%=): Takes the modulus of the left operand with the right
operand and assigns the result to the left operand.

ng
let x = 10;
x %= 3; // x is now 1

ni
3. Comparison Operators

ar
Comparison operators are used to compare two values and return a boolean
(true or false). Le
ve
si
er
m
Em

34
Equal to (==): Returns true if the operands are equal (with type coercion).

5 == "5"; // true

Strictly Equal to (===): Returns true if the operands are equal and of the same

ng
type (no type coercion).
5 === "5"; // false

ni
5 === 5; // true

ar

Le
Not Equal to (!=): Returns true if the operands are not equal (with type
coercion).
javascript
ve
Copy code
5 != "5"; // false
si


er

Strictly Not Equal to (!==): Returns true if the operands are not equal or not of
m

the same type.


javascript
Em

Copy code
5 !== "5"; // true
5 !== 5; // false

35
Greater Than (>): Returns true if the left operand is greater than the right
operand.
javascript
Copy code
10 > 5; // true

ng
Less Than (<): Returns true if the left operand is less than the right operand.

ni
javascript
Copy code

ar
10 < 5; // false

● Le
Greater Than or Equal to (>=): Returns true if the left operand is greater than
ve
or equal to the right operand.
javascript
si

Copy code
10 >= 10; // true
er


m

Less Than or Equal to (<=): Returns true if the left operand is less than or
Em

equal to the right operand.


javascript
Copy code
10 <= 5; // false

36
4. Logical Operators

Logical operators are used to combine or invert boolean values.

ng
ni
ar
Logical AND (&&): Returns true if both operands are true.
javascript
Copy code
Le
true && true; // true
ve
true && false; // false
si


er

Logical OR (||): Returns true if at least one of the operands is true.


javascript
m

Copy code
true || false; // true
Em

false || false; // false

Logical NOT (!): Returns the opposite boolean value.


javascript

37
Copy code
!true; // false
!false; // true

5. Bitwise Operators

ng
Bitwise operators perform operations on binary representations of numbers.

ni
ar
Le
ve
si
er
m

AND (&): Performs a bitwise AND operation.


Em

javascript
Copy code
5 & 1; // 1 (binary: 0101 & 0001 = 0001)

38
OR (|): Performs a bitwise OR operation.
javascript
Copy code
5 | 1; // 5 (binary: 0101 | 0001 = 0101)

ng
XOR (^): Performs a bitwise XOR operation.
javascript

ni
Copy code
5 ^ 1; // 4 (binary: 0101 ^ 0001 = 0100)

ar

NOT (~): Inverts the bits of its operand.


Le
javascript
ve
Copy code
~5; // -6 (binary: 0101 -> 1010, which is -6 in two's
si

complement)
er


m

Left Shift (<<): Shifts the bits of its operand to the left.
javascript
Em

Copy code
5 << 1; // 10 (binary: 0101 << 1 = 1010)

Right Shift (>>): Shifts the bits of its operand to the right.
javascript

39
Copy code
5 >> 1; // 2 (binary: 0101 >> 1 = 0010)

6. Ternary Operator

The ternary operator is a shorthand for the if-else statement. It is written as

ng
condition ? expr1 : expr2.

ni
ar
Le
ve

Syntax:
si

javascript
er

Copy code
condition ? valueIfTrue : valueIfFalse;
m


Em

Example:
javascript
Copy code
let age = 18;
let canVote = (age >= 18) ? "Yes" : "No";
console.log(canVote); // "Yes"

40

7. Type Operators

Type operators are used to get information about types and to convert between
types.

typeof: Returns the type of a variable or expression.

ng
javascript
Copy code

ni
typeof 42; // "number"

ar
typeof "hello"; // "string"
typeof true; // "boolean"


Le
instanceof: Returns true if the object is an instance of a specified object
ve

type.
javascript
si

Copy code
er

let arr = [1, 2, 3];


console.log(arr instanceof Array); // true
m

console.log(arr instanceof Object); // true


Em

8. String Operators

Strings can be concatenated using the + operator.

41
Concatenation (+): Combines two strings.
javascript
Copy code
let greeting = "Hello, " + "World!";
console.log(greeting); // "Hello, World!"

ng

Concatenation Assignment (+=): Adds and assigns the resulting string.

ni
javascript
Copy code

ar
let message = "Hello";
message += ", World!";
console.log(message); // "Hello, World!"
Le
ve

si

These operators are the building blocks of JavaScript. They allow you to perform
er

various operations on data, control the flow of your program, and manipulate
values. Understanding how and when to use each operator will greatly enhance
m

your ability to write efficient and effective JavaScript code.


Em

42
4. Control Flow
Control flow in JavaScript refers to the order in which the code is executed. By
default, JavaScript code is executed line by line, from top to bottom. However,
you can alter this order using control flow statements like conditionals (if, else,

ng
switch) and loops (for, while, do...while). These structures allow you to
make decisions, repeat code, and handle complex logic.

ni
ar
Le
ve

Program Flow.
si
er
m
Em

43
1. Conditional Statements

Conditional statements are used to perform different actions based on different


conditions.

ng
ni
ar
Le
ve
si
er

1.1 if Statement
m

The if statement executes a block of code if a specified condition is true.


Em

44
ng
ni
ar
Syntax:
Le
ve

if (condition) {
// code to be executed if the condition is true
si

}
er

Example:
m
Em

let age = 18;


if (age >= 18) {
console.log("You are an adult.");
}

45
1.2 else Statement

The else statement executes a block of code if the condition in the if statement
is false.

ng
ni
ar
Le
ve
si
er

Syntax:
m

if (condition) {
Em

// code to be executed if the condition is true


} else {
// code to be executed if the condition is false
}

46
Example:

let age = 16;


if (age >= 18) {
console.log("You are an adult.");
} else {

ng
console.log("You are not an adult.");
}

ni
ar
1.3 else if Statement

Le
The else if statement specifies a new condition if the first condition is false.
ve
si
er
m
Em

47
ng
ni
ar
Le
ve
si
er
m
Em

Syntax:

if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition is true

48
} else {
// code to be executed if both conditions are false
}

Example:

ng
let age = 20;

ni
if (age < 13) {

ar
console.log("You are a child.");
} else if (age >= 13 && age < 20) {
console.log("You are a teenager.");
} else {
Le
console.log("You are an adult.");
ve

}
si
er

1.4 switch Statement


m

The switch statement is used to perform different actions based on different


conditions, specifically when the conditions are based on a single expression.
Em

49
ng
ni
ar
Le
ve
si

Syntax:
er
m

switch (expression) {
case value1:
Em

// code to be executed if expression === value1


break;
case value2:
// code to be executed if expression === value2
break;
default:

50
// code to be executed if expression doesn't match any case
}

Example:

let day = "Monday";


switch (day) {

ng
case "Monday":
console.log("Start of the work week.");

ni
break;

ar
case "Wednesday":
console.log("Midweek.");
break;
case "Friday":
Le
console.log("End of the work week.");
ve
break;
default:
si

console.log("It's the weekend!");


er

}
m

2. Looping Statements
Em

Looping statements allow you to repeat a block of code as long as a specified


condition is true.

51
ng
ni
ar
2.1 for Loop
Le
The for loop is used when you know the number of iterations in advance.
ve
si
er
m
Em

52
ng
ni
ar
Le
ve

Syntax:
si

for (initialization; condition; increment) {


// code to be executed for each iteration
er

}
m
Em

53
Example:

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


console.log("Iteration number: " + i);
}

ng
2.2 while Loop

ni
The while loop repeats a block of code as long as the condition is true.

ar
Syntax:

while (condition) {

}
Le
// code to be executed as long as the condition is true
ve
si

Example:

let i = 0;
er

while (i < 5) {
m

console.log("Iteration number: " + i);


i++;
Em

2.3 do...while Loop

The do...while loop is similar to the while loop, but the block of code is
executed at least once before the condition is tested.

54
ng
ni
ar
Le
ve
si
er

Syntax:
m
Em

do {
// code to be executed at least once
} while (condition);

Example:

55
let i = 0;
do {
console.log("Iteration number: " + i);
i++;
} while (i < 5);

ng
3. Control Flow Statements

ni
These statements alter the normal flow of execution.

ar
3.1 break Statement

Le
The break statement is used to exit a loop or a switch statement prematurely.
ve
si
er
m
Em

56
Example in a for loop:

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


if (i === 5) {
break; // exit the loop when i is 5
}

ng
console.log("Iteration number: " + i);
}

ni

ar
3.2 continue Statement
Le
The continue statement skips the rest of the current loop iteration and moves
on to the next iteration.
ve

Example in a for loop:


si

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


er

if (i === 5) {
m

continue; // skip the iteration when i is 5


}
Em

console.log("Iteration number: " + i);


}

57
ng
ni
ar
3.3 return Statement

Le
The return statement exits a function and optionally returns a value to the
function caller.
ve
Example:
si

function add(a, b) {
er

return a + b; // exit the function and return the sum


}
m

let result = add(3, 5); // result is 8


Em

console.log(result);

4. Ternary Operator

The ternary operator is a shorthand way to handle simple if-else logic. It’s
often used as a shorter alternative for simple conditional expressions.

58
ng
ni
ar
Syntax:
Le
condition ? expr1 : expr2;
ve
si

Example:
er

let age = 18;


m

let canVote = (age >= 18) ? "Yes" : "No";


Em

console.log(canVote); // "Yes"

These control flow structures are essential for managing how your code
executes. By using conditionals, loops, and control flow statements, you can

59
write JavaScript programs that make decisions, handle repetition, and respond to
different conditions, making your code more dynamic and powerful.

Problem Solving Home work | Submit The code

ng
Here are some basic JavaScript problems to practise control flow statements and
functions. These problems will help you get comfortable with if, else if,

ni
else, switch, and loops (for, while, do...while).

ar
Problem 1: Even or Odd

Le
Task: Write a function isEvenOrOdd(number) that takes a number as an
argument and returns "Even" if the number is even, and "Odd" if the number is
odd.
ve

Code :
si

function isEvenOrOdd(number) {
// Your code here
er

}
m

Problem 2: FizzBuzz
Em

Task: Write a function fizzBuzz(n) that prints the numbers from 1 to n. But for
multiples of three, print "Fizz" instead of the number, and for the multiples of
five, print "Buzz". For numbers which are multiples of both three and five, print
"FizzBuzz".

Start with this :

60
function fizzBuzz(n) {
// Your code here
}

Problem 3: Maximum of Three Numbers

ng
Task: Write a function maxOfThree(a, b, c) that returns the largest of three
numbers.

ni
Start with this code :

ar
function maxOfThree(a, b, c) {
// Your code here
}
Le
Problem 4: Leap Year Checker
ve

Task: Write a function isLeapYear(year) that returns true if the given year is
si

a leap year, and false otherwise. A leap year is divisible by 4, but not by 100
er

unless it is also divisible by 400.


m

Start with this code :

function isLeapYear(year) {
Em

// Your code here


}

Problem 5: Simple Calculator

61
Task: Write a function calculate(a, b, operator) that takes two numbers
and an operator as arguments and returns the result of the operation. The
operator can be "+", "-", "*", or "/". Use a switch statement.

Start with this code :

function calculate(a, b, operator) {

ng
// Your code here
}

ni
Problem 6: Sum of Digits

ar
Task: Write a function sumOfDigits(number) that returns the sum of all the

Le
digits in a given number. Use a while loop to iterate through the digits.

Start with this code :


ve

function sumOfDigits(number) {
si

// Your code here


}
er
m

Problem 7: Factorial
Em

Task: Write a function factorial(n) that returns the factorial of a given


number n. Use a for loop.

Start with this code :

function factorial(n) {
// Your code here
}

62
Problem 8: Reverse a String

Task: Write a function reverseString(str) that takes a string as input and


returns the reversed string. Use a for loop.

ng
function reverseString(str) {
// Your code here
}

ni
ar
Problem 9: Count Vowels

Le
Task: Write a function countVowels(str) that takes a string and returns the
number of vowels (a, e, i, o, u) in the string. Use a for loop and if conditions.
ve

Start with this code :

function countVowels(str) {
si

// Your code here


er

}
m

Problem 10: Prime Number Checker


Em

Task: Write a function isPrime(n) that returns true if the given number n is a
prime number, and false otherwise. Use a for loop and if conditions.

Start with this code :

function isPrime(n) {
// Your code here
}

63
Problem 11: Find the Largest Element in an Array

Task: Write a function findLargest(arr) that takes an array of numbers and


returns the largest element in the array. Use a for loop.

ng
Start with this code :

function findLargest(arr) {

ni
// Your code here
}

ar
Problem 12: Palindrome Checker
Le
Task: Write a function isPalindrome(str) that checks whether a given string
ve
is a palindrome (a string that reads the same backward as forward). Use a for
loop and if conditions.
si

Start with this code :


er

function isPalindrome(str) {
// Your code here
m

}
Em

Problem 13: Print a Pattern

Task: Write a function printPattern(n) that prints the following pattern for a
given n:

markdown

64
*
**
***
****
*****

Use a nested for loop.

ng
Start with this :

ni
function printPattern(n) {
// Your code here

ar
}

Le
Problem 14: Count Occurrences of a Character
ve
Task: Write a function countCharacter(str, char) that takes a string and a
character as input and returns the number of times the character appears in the
si

string. Use a for loop and if conditions.


er

Start here :
m

function countCharacter(str, char) {


// Your code here
Em

Problem 15: Find the Second Largest Element in an Array

Task: Write a function findSecondLargest(arr) that takes an array of


numbers and returns the second-largest element in the array. Use a for loop.

65
Start here :

function findSecondLargest(arr) {
// Your code here
}

These problems will give you a good range of practice with different control flow

ng
techniques in JavaScript.

ni
ar
5. JavaScript Functions
Le
Functions are one of the fundamental building blocks in JavaScript. A function is
ve
a block of code designed to perform a particular task. You can define a function
once and reuse it throughout your code. Functions help make your code more
modular, readable, and maintainable.
si

Before that, take a look at those math functions


er
m
Em

66
Em
m
er
si
ve
Le
ar
ni
ng

67
Em Code Functions

m
er
si
ve
Le
ar
ni
ng

68
1. Built in ( Pre Defined) Functions

ng
ni
ar
Le
ve
si
er
m
Em

2. User Defined Function

1. Defining a Function

A function is defined using the function keyword, followed by a name,


parentheses (), and a block of code enclosed in curly braces {}.

69
ng
ni
ar
Le
ve

Syntax:
si

function functionName(parameters) {
// code to be executed
er

}
m

Example:
Em

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

70
In this example, greet is the name of the function, and the console.log
statement is the code that will be executed when the function is called.

ng
ni
ar
2. Calling a Function Le
To execute the code inside a function, you need to "call" the function. You do this
ve
by writing the function name followed by parentheses.
si
er
m
Em

Example:

greet(); // This will output: "Hello, world!"

71
3. Function Parameters

Functions can accept inputs, called parameters, which allow you to pass values
into the function.

ng
ni
ar
Le
ve
si
er

Syntax:
m

function functionName(parameter1, parameter2) {


Em

// code to be executed
}

Example:

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

greet("Alice"); // This will output: "Hello, Alice!"


greet("Bob"); // This will output: "Hello, Bob!"

ng
Here, name is a parameter of the greet function, and when you call

ni
greet("Alice"), "Alice" is passed as an argument to the name parameter.

ar
4. Return Statement
Le
Functions can return a value back to the caller using the return statement.
Once the return statement is executed, the function stops, and the value is
ve
returned.

Syntax:
si

function functionName(parameters) {
er

// code to be executed
return value;
m

}
Em

Example:

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

73
}

let result = add(3, 4); // result is 7


console.log(result); // This will output: 7

ng
Here, the add function takes two parameters, a and b, adds them, and returns
the result. The value returned by the function can be stored in a variable or used

ni
directly.

ar
5. Function Expressions

Le
Functions can also be defined as expressions. A function expression is a function
that is stored in a variable.
ve
Syntax:
si

let variableName = function(parameters) {


// code to be executed
er

};
m
Em

Example:

let sayHello = function() {


console.log("Hello!");
};

74
sayHello(); // This will output: "Hello!"

Function expressions are often used for functions that are passed as arguments
or used in callbacks.

ng
6. Arrow Functions

Arrow functions provide a shorter syntax for writing function expressions. They

ni
are particularly useful for writing anonymous functions.

ar
Le
ve

Syntax:
si
er

let functionName = (parameters) => {


m

// code to be executed
};
Em

Example:

let add = (a, b) => {


return a + b;
};

75
console.log(add(2, 3)); // This will output: 5

If the function body contains only a single expression, you can omit the curly
braces and the return keyword.

ng
Shortened Syntax:

ni
let add = (a, b) => a + b;
console.log(add(2, 3)); // This will output: 5

ar
7. Default Parameters
Le
ve
In JavaScript, you can assign default values to function parameters. If no
argument is provided for that parameter when the function is called, the default
value is used.
si

Syntax:
er
m

function functionName(parameter1 = defaultValue1, parameter2 =


defaultValue2) {
Em

// code to be executed
}

Example:

76
function greet(name = "stranger") {
console.log("Hello, " + name + "!");
}

greet("Alice"); // This will output: "Hello, Alice!"


greet(); // This will output: "Hello, stranger!"

ng
ni
In this example, if no argument is provided when calling greet(), the default

ar
value "stranger" is used for the name parameter.

8. Function Scope
Le
Functions create their own scope. Variables declared inside a function are local
to that function and cannot be accessed outside of it.
ve

Example:
si
er

function myFunction() {
let message = "Hello, inside the function!";
m

console.log(message);
}
Em

myFunction(); // This will output: "Hello, inside the function!"


console.log(message); // This will throw an error because
'message' is not defined outside the function

77
In this example, the variable message is only accessible within the myFunction
function.

9. Nested Functions

Functions can be nested inside other functions. The inner function has access to
the variables and parameters of the outer function.

ng
Example:

ni
ar
function outerFunction(outerVariable) {
function innerFunction(innerVariable) {
Le
console.log("Outer Variable: " + outerVariable);
console.log("Inner Variable: " + innerVariable);
}
ve

innerFunction("inner");
}
si
er

outerFunction("outer");
// This will output:
m

// Outer Variable: outer


Em

// Inner Variable: inner

In this example, the innerFunction can access the outerVariable from the
outerFunction.

78
These concepts provide a solid foundation for working with functions in
JavaScript. Functions are essential for organising your code, creating reusable
pieces of logic, and making your code more readable and maintainable.

Test your JS Function Understanding

ng
Here are 10 questions designed to test your understanding of JavaScript

ni
functions:

ar
1. Basic Function Definition

Question: How do you define a basic function in JavaScript that takes two
numbers as input and returns their sum?
Le
Answer:
ve

function sum(a, b) {
si

return a + b;
}
er
m
Em

2. Function Expression

Question: What is the difference between a function expression and a function


declaration in JavaScript? Write an example of a function expression.

Answer:

● Function Declaration: A function declaration is hoisted, meaning it can be


called before it's defined in the code.

79
● Function Expression: A function expression is not hoisted, meaning it
cannot be called before it's assigned.

Example of a Function Expression:

const multiply = function(a, b) {


return a * b;

ng
};

ni
ar
3. Default Parameters

Question: Write a function greet that takes two arguments: name and
Le
greeting. If no greeting is provided, it should default to "Hello". For example,
greet("Mehammed") should return "Hello, Mehammed".
ve

Answer:
si

function greet(name, greeting = "Hello") {


er

return `${greeting}, ${name}`;


}
m

console.log(greet("John")); // "Hello, Mehammed"


Em

console.log(greet("Jane", "Hi")); // "Hi, Mehammed"

4. Function Scope

Question: What is the difference between function scope and block scope in
JavaScript? Provide an example to explain your answer.

80
Answer:

● Function Scope: Variables declared with var inside a function are


available throughout the function.
● Block Scope: Variables declared with let and const are available only
within the block {} in which they are defined.

ng
Example:

ni
function testFunctionScope() {
var x = 1;

ar
if (true) {
var x = 2; // Function-scoped variable (var)

}
console.log(x); // 2
Le
ve
console.log(x); // 2 (because var is function-scoped)
}
si

function testBlockScope() {
er

let y = 1;
if (true) {
m

let y = 2; // Block-scoped variable (let)


Em

console.log(y); // 2
}
console.log(y); // 1 (because let is block-scoped)
}

5. Arrow Functions

81
Question: Rewrite the following function using the arrow function syntax:

function multiply(a, b) {
return a * b;
}

Answer:

ng
const multiply = (a, b) => a * b;

ni
ar
6. Callback Functions
Le
Question: What is a callback function in JavaScript? Write an example where a
callback function is passed to another function.
ve

Answer:
si

● A callback function is a function passed as an argument to another


er

function and is executed after some operation is completed.


m

Example:
Em

function fetchData(callback) {
// Simulating fetching data
console.log("Fetching data...");
setTimeout(() => {
callback("Data received");
}, 1000);
}

82
function processData(data) {
console.log("Processing: " + data);
}

fetchData(processData);

ng
ni
7. Function as a Return Value

ar
Question: Write a function createMultiplier(multiplier) that returns a
new function. The new function should multiply any number passed to it by the
original multiplier. For example:
Le
ve
const multiplyBy2 = createMultiplier(2);
multiplyBy2(5); // should return 10
si

Answer:
er

function createMultiplier(multiplier) {
m

return function(number) {
return number * multiplier;
Em

};
}

const multiplyBy2 = createMultiplier(2);


console.log(multiplyBy2(5)); // 10

83
8. IIFE (Immediately Invoked Function Expression)

Question: What is an IIFE (Immediately Invoked Function Expression)? Write an


example of an IIFE in JavaScript and explain its use case.

Answer:

● An IIFE is a function that is defined and immediately executed. It is often

ng
used to avoid polluting the global namespace or to create a local scope for
variables.

ni
Example:

ar
(function() {
Le
console.log("This function is invoked immediately!");
})();
ve
Use case: It’s used when you need to run some code right away and
encapsulate variables to avoid global scope pollution.
si
er

9. Higher-Order Functions
m

Question: What is a higher-order function in JavaScript? Write a higher-order


Em

function repeatNTimes that takes a function and a number n, and calls the
given function n times.

Answer:

● A higher-order function is a function that either takes a function as an


argument or returns a function.

84
Example:

function repeatNTimes(func, n) {
for (let i = 0; i < n; i++) {
func();
}

ng
}

function sayHello() {

ni
console.log("Hello!");

ar
}

repeatNTimes(sayHello, 3);
// Output: "Hello!" (3 times)
Le
ve

10. Closures
si
er

Question: What is a closure in JavaScript? Provide an example to explain how


closures work and how variables are retained even after the outer function has
m

executed.
Em

Answer:

● A closure is a function that retains access to the variables of its outer


function, even after the outer function has completed execution.

Example:

function outerFunction(outerVariable) {

85
return function innerFunction(innerVariable) {
console.log(`Outer Variable: ${outerVariable}`);
console.log(`Inner Variable: ${innerVariable}`);
};
}

ng
const newFunction = outerFunction("Outside");
newFunction("Inside");

ni
// Output:

ar
// Outer Variable: Outside
// Inner Variable: Inside
Le
ve
Explanation: The innerFunction retains access to the outerVariable even
after outerFunction has finished executing, demonstrating the concept of
si

closures.
er
m
Em

These questions touch on different aspects of JavaScript functions, from basic


syntax to more advanced topics like closures, callback functions, and
higher-order functions. Answering these questions will help you assess how well
you understand JavaScript functions.

86
6. JavaScript Objects
In JavaScript, an object is a collection of properties and methods. Properties are
values associated with the object, while methods are functions that can be
performed on the object. Objects allow you to group related data and functions
together in a single entity.

ng
ni
ar
Le
ve
si

Types of Objects
er

JavaScript objects come in various types and forms, each serving different
m

purposes. Here are the key types of JavaScript objects:


Em

87
ng
ni
ar
1. Native (Built-in) Objects

Le
Native objects are provided by the JavaScript language itself. These are
standard objects that come with the language and can be used in any JavaScript
environment.
ve
si
er
m
Em

2. Host Objects

Host objects are objects provided by the environment in which the JavaScript
code is run, like the browser or Node.js. These are not part of the JavaScript
language itself but are provided by the host environment.

Here are the browser window object.

88
ng
ni
ar
Le
ve
Document object
si
er
m
Em

89
3. Custom (User-defined) Objects

Custom objects are those created by developers for specific use cases. These
are often created using object literals, constructor functions, classes, or factory
functions.

ng
User-defined Objects

ni
ar
1. Creating an Object

Le
There are several ways to create objects in JavaScript:
ve
si
er
m
Em

90
1. Using Object Literal

const person = {
name: "Mehammed",
age: 27,
profession: "Software Engineer",

ng
greet: function() {
console.log("Hello, my name is " + this.name);

ni
}
};

ar
In this example: Le
● name, age, and profession are properties.
ve
● greet is a method.
si

You can access properties using dot notation or bracket notation:


er

console.log(person.name); // "Mehammed"
console.log(person['age']); // 27
m
Em

2. Using the new Object() Syntax

This is an older way of creating an object using the Object


constructor.

91
const car = new Object();
car.brand = "Toyota";
car.model = "Camry";
car.year = 2020;

console.log(car.brand); // "Toyota"

ng
3. Using a Constructor Function

ni
Constructor functions are used to create multiple instances

ar
of an object. This is useful when you need to create many
objects with the same properties and methods.
Le
function Person(name, age, profession) {
this.name = name;
ve

this.age = age;
this.profession = profession;
si

}
er

const john = new Person("Mehammed", 30, "Developer");


m

const jane = new Person("Abdu", 28, "Designer");


Em

console.log(john.name); // "Mehammed"
console.log(jane.profession); // "Designer"

92
2. Accessing and Modifying Object Properties

● Accessing Properties:

console.log(person.name); // "Mehammed"

ng
● Modifying Properties:

person.age = 35;

ni
console.log(person.age); // 35

ar
● Adding New Properties: Le
person.country = "Ethiopia";
ve
console.log(person.country); // "Ethiopia"
si

● Deleting Properties:
er

delete person.profession;
m

console.log(person.profession); // undefined
Em

3. Methods in Objects

A method is a function associated with an object. You can call methods using dot
notation:

93
person.greet(); // "Hello, my name is Mehammed"

The keyword this refers to the object it belongs to. In this case, this.name
refers to the name property of the person object.

ng
4. Nested Objects

ni
Objects can also contain other objects as properties, known as nested objects:

ar
const employee = {
name: "Abebe",
Le
department: {
ve
name: "Engineering",
manager: "Mehammed"
si

}
er

};
m

console.log(employee.department.name); // "Engineering"
Em

5. Object Methods

JavaScript provides many built-in methods for working with objects:

94
ng
ni
ar
Le
ve
● Object.keys(): Returns an array of the object’s keys (property names).

console.log(Object.keys(person)); // ["name", "age", "greet",


si

"country"]
er
m

● Object.values(): Returns an array of the object’s values.


Em

console.log(Object.values(person)); // ["John", 35, ƒ, "USA"]

● Object.assign(): Copies properties from one or more source objects to a


target object.

95
const target = { a: 1 };
const source = { b: 2, c: 3 };
Object.assign(target, source);
console.log(target); // { a: 1, b: 2, c: 3 }

ng
ni
6. Constructor Functions

ar
A constructor function is a special way of creating objects. It allows you to
create multiple objects with similar properties and methods.

Example:
Le
function Car(make, model, year) {
ve

this.make = make;
this.model = model;
si

this.year = year;
er

}
m

const myCar = new Car("Toyota", "Camry", 2020);


console.log(myCar.make); // "Toyota"
Em

console.log(myCar.year); // 2020

7. The this Keyword

96
In JavaScript, this refers to the current object. In a method, this refers to the
object calling the method:

const student = {
name: "Omer",
introduce: function() {

ng
console.log("Hi, I'm " + this.name);
}
};

ni
ar
student.introduce(); // "Hi, I'm Omer"

Le
8. Object Destructuring
ve

Destructuring allows you to extract values from objects easily.


si

Example:
er

const user = {
m

name: "Alice",
age: 25,
Em

city: "New York"


};

const { name, age } = user;


console.log(name); // "Alice"
console.log(age); // 25

97
9. Checking for Properties

You can check whether an object has a certain property using the in operator or
hasOwnProperty() method:

ng
ni
console.log("name" in person); // true
console.log(person.hasOwnProperty("age")); // true

ar
10. Iterating Over Object Properties
Le
ve
You can iterate over an object's properties using a for...in loop:
si

for (let key in person) {


er

console.log(key + ": " + person[key]);


}
m

// Output:
Em

// name: Mehammed
// age: 35
// greet: function
// country: Ethiopia

98
Example: Complete Object with Methods

const car = {
brand: "Tesla",
model: "Model 3",
year: 2022,
start: function() {

ng
console.log(`${this.brand} ${this.model} is starting.`);
},

ni
drive: function() {

ar
console.log(`${this.brand} ${this.model} is driving.`);
}
};
Le
car.start(); // "Tesla Model 3 is starting."
ve
car.drive(); // "Tesla Model 3 is driving."
si
er

Conclusion
m

JavaScript objects are a versatile and fundamental feature for organising and
structuring data. They allow you to store key-value pairs, define methods, and
Em

create complex structures. Understanding objects is crucial for writing effective


and scalable JavaScript code.

99
Questions to test your Understanding

Here are 10 questions to test your understanding of JavaScript objects:

1. Basic Object Creation

Question: How do you create an object using the object literal syntax? Create an

ng
object person with properties name as "Mehammed", age as 30, and city as
"Addis Ababa".

ni
Answer:

ar
const person = {
name: "Mehammed",
age: 30,
Le
city: "Addis Ababa"
ve
};
si
er

2. Accessing Object Properties


m

Question: Given the object below, how do you access the city property using
Em

both dot notation and bracket notation?

const user = {
name: "Mehammed",
city: "Addis Ababa",
age: 25
};

100
Answer:

Dot notation:

console.log(user.city); // "Los Angeles"

ng
Bracket notation:

ni
console.log(user["city"]); // "Los Angeles"

ar
Le
3. Adding and Updating Properties
ve

Question: How do you add a new property email to the object person and
si

update the existing age property?


er

const person = {
m

name: "Mehammed",
age: 30
Em

};

Answer:

Add new property:

person.email = "[email protected]";

101
Update existing property:

person.age = 31;

ng
ni
4. Deleting Object Properties

ar
Question: How do you delete the age property from the object person?

const person = {
Le
name: "Mehammed",
ve
age: 30,
city: "Addis Ababa"
si

};
er

Answer:
m

delete person.age;
Em

console.log(person);
// { name: "Mehammed", city: "Addis Ababa" }

5. Iterating Over Object Properties

102
Question: Write a for...in loop to iterate over all properties of the object car
and log the keys and values.

const car = {
brand: "Toyota",
model: "Camry",

ng
year: 2020
};

ni
ar
Answer:

for (let key in car) {


Le
console.log(`${key}: ${car[key]}`);
}
ve
// Output:
// brand: Toyota
si

// model: Camry
// year: 2020
er
m
Em

6. Object Methods

Question: How do you define a method greet inside the person object that
logs the message "Hello, my name is [name]", where [name] is the
name of the person?

Answer:

103
const person = {
name: "Mehammed",
age: 30,
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}

ng
};

ni
person.greet();
// Output: "Hello, my name is John"

ar
7. Object Destructuring
Le
ve
Question: Using object destructuring, extract the name and age properties from
the person object.
si
er

const person = {
name: "John",
m

age: 30,
city: "New York"
Em

};

Answer:

const { name, age } = person;

104
console.log(name); // "John"
console.log(age); // 30

8. Nested Objects

ng
Question: Given the following object, how would you access the city of the
address property?

ni
ar
const company = {
name: "Tech Corp",
address: {
city: "San Francisco",
Le
zip: "94111"
ve
}
};
si
er

Answer:
m

console.log(company.address.city); // "San Francisco"


Em

9. Using Object.keys() and Object.values()

Question: How would you use Object.keys() and Object.values() to get


the keys and values of the object book?

105
const book = {
title: "JavaScript Essentials",
author: "Jane Doe",
pages: 300
};

ng
Answer:

ni
Get keys:

ar
const keys = Object.keys(book);
Le
console.log(keys); // ["title", "author", "pages"]
ve

Get values:
si

const values = Object.values(book);


er

console.log(values); // ["JavaScript Essentials", "Jane Doe",


m

300]
Em

10. Prototypes and Inheritance

Question: What is the prototype of an object in JavaScript, and how can you add
a method to an object's prototype?

106
Answer:

● Prototype: In JavaScript, every object has a prototype, which is another


object from which the current object inherits properties and methods. The
prototype provides a mechanism for inheritance in JavaScript.

Adding a method to a prototype: You can add a method to an object's

ng
prototype like this:

ni
function Person(name, age) {
this.name = name;

ar
this.age = age;
}
Le
// Adding a method to Person's prototype
ve
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
si

};
er

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


m

john.greet(); // Output: "Hello, my name is John"


Em

These answers cover essential aspects of JavaScript objects, including creation,


manipulation, methods, destructuring, nested objects, and prototyping

107
7. JavaScript Arrays
Arrays in JavaScript are used to store multiple values in a single variable. Arrays
are one of the most common data structures in JavaScript. Here’s a detailed
guide on how to work with arrays:

ng
ni
ar
Le
ve

1. Creating Arrays
si

You can create arrays using:


er

Array literal notation (most common):


m

const fruits = ["apple", "banana", "cherry"];


Em

Array constructor:

const fruits = new Array("apple", "banana", "berry");

108
2. Accessing Array Elements

Array elements are accessed by their index. Indexes start from 0 (zero-based
index):

const fruits = ["apple", "banana", "cherry"];


console.log(fruits[0]); // Output: "apple"

ng
console.log(fruits[2]); // Output: "cherry"

ni
3. Modifying Array Elements

ar
You can modify array elements by accessing their index:

fruits[1] = "orange";
Le
console.log(fruits); // Output: ["apple", "orange", "cherry"]
ve

4. Array Properties
si

Length: The length property returns the number of elements in the array:
er
m

console.log(fruits.length); // Output: 3
Em

5. Common Array Methods

109
ng
ni
ar
Le
Here are some important array methods:

push(): Adds an element to the end of the array.


ve

fruits.push("grape");
si

console.log(fruits); // Output: ["apple", "orange", "cherry",


"grape"]
er
m

pop(): Removes the last element from the array.


Em

fruits.pop();
console.log(fruits); // Output: ["apple", "orange", "cherry"]

shift(): Removes the first element from the array.

110
fruits.shift();
console.log(fruits); // Output: ["orange", "cherry"]

unshift(): Adds an element to the beginning of the array.

ng
fruits.unshift("kiwi");

ni
console.log(fruits); // Output: ["kiwi", "orange", "cherry"]

ar
indexOf(): Finds the index of an element.
Le
const index = fruits.indexOf("orange");
ve
console.log(index); // Output: 1
si
er

includes(): Checks if the array contains a specific element.


m

const hasApple = fruits.includes("apple");


Em

console.log(hasApple); // Output: false

slice(): Returns a portion of an array without modifying the original array.

const sliced = fruits.slice(1, 3);

111
console.log(sliced); // Output: ["orange", "cherry"]

splice(): Adds or removes elements from an array.

ng
fruits.splice(1, 1, "strawberry"); // Replaces 1 element at
index 1

ni
console.log(fruits); // Output: ["kiwi", "strawberry", "cherry"]

ar
Le
ve
si
er
m
Em

112
6. Iterating Over Arrays

You can loop through an array using different loops:

for loop:

for (let i = 0; i < fruits.length; i++) {

ng
console.log(fruits[i]);
}

ni
ar
forEach(): A higher-order function to iterate over arrays.
Le
fruits.forEach((fruit) => {
ve
console.log(fruit);
});
si
er

map(): Returns a new array by transforming every element.


m
Em

const upperFruits = fruits.map(fruit => fruit.toUpperCase());


console.log(upperFruits); // Output: ["KIWI", "STRAWBERRY",
"CHERRY"]

113
7. Multi-dimensional Arrays

Arrays can hold other arrays (multi-dimensional arrays):

const matrix = [
[1, 2, 3],
[4, 5, 6],

ng
[7, 8, 9]
];

ni
console.log(matrix[1][2]); // Output: 6

ar
8. Destructuring Arrays
Le
You can use destructuring to extract values from an array into variables:
ve

const [first, second] = fruits;


si

console.log(first); // Output: "kiwi"


er

console.log(second); // Output: "strawberry"


m
Em

9. Spread Operator in Arrays

The spread operator (...) can be used to copy and merge arrays:

Copying an array:

const newFruits = [...fruits];

114
Merging arrays:

const moreFruits = ["grape", "mango"];


const allFruits = [...fruits, ...moreFruits];

ng
console.log(allFruits); // Output: ["kiwi", "strawberry",
"cherry", "grape", "mango"]

ni
ar
10. Array Challenges Le
Here are a few array challenges for practice:
ve

1. Write a function that returns the largest number in an array.


2. Write a function that removes duplicates from an array.
si

3. Write a function that finds the sum of all numbers in an array.


er

4. Write a function that reverses an array.

By mastering arrays, you'll be better equipped to handle collections of data in


m

JavaScript! Let me know if you'd like more examples or explanations on any part
Em

of arrays.

8. JavaScript String
In JavaScript, a string is a sequence of characters used to represent text.
Strings are one of the most commonly used data types, and JavaScript provides
many built-in methods to work with them.

115
ng
ni
ar
Le
Here's an overview of how to work with strings in JavaScript:
ve

1. Creating Strings
si

There are three ways to create a string in JavaScript:


er

Using single quotes:


m
Em

const singleQuoteString = 'Hello, World!';

Using double quotes:

const doubleQuoteString = "Hello, World!";

116
Using backticks (Template literals): These are mainly used for string
interpolation and multi-line strings:

const templateLiteral = `Hello, World!`;

ng
ni
2. String Interpolation (Template Literals)

ar
Template literals (backticks) allow you to embed expressions inside a string using
${}:

const name = Mehammed;


Le
const greeting = `Hello, ${name}!`; // Output: "Hello,
ve
Mehammed!"
si

You can also use template literals for multi-line strings:


er

const message = `This is a multi-line string


m

that spans over multiple lines`;


Em

3. Common String Methods

JavaScript provides a variety of methods to manipulate and work with strings.

117
ng
ni
ar
Le
ve
si

String Length
er

The length property returns the number of characters in a string:


m

const text = 'Hello';


Em

console.log(text.length); // Output: 5

Accessing Characters
You can access individual characters in a string using indexing:

118
const text = 'Hello';
console.log(text[0]); // Output: "H"
console.log(text[4]); // Output: "o"

Changing Case
toUpperCase(): Converts a string to uppercase:

ng
const text = 'hello';

ni
console.log(text.toUpperCase()); // Output: "HELLO"

ar
Le
toLowerCase(): Converts a string to lowercase:
ve
const text = 'HELLO';
console.log(text.toLowerCase()); // Output: "hello"
si
er

String Concatenation
You can join two or more strings using the + operator or concat() method:
m
Em

const firstName = 'John';


const lastName = 'Doe';
console.log(firstName + ' ' + lastName); // Output: "John Doe"

Or using concat():

console.log(firstName.concat(' ', lastName)); // Output: "John

119
Doe"

Extracting a Substring
slice(): Extracts part of a string based on the given start and end indexes:

const text = 'Hello, World!';

ng
console.log(text.slice(0, 5)); // Output: "Hello"
console.log(text.slice(-6)); // Output: "World!"

ni
ar
substring(): Similar to slice(), but cannot accept negative indexes:

console.log(text.substring(0, 5)); Le // Output: "Hello"


ve
substr(): Extracts a part of the string based on the starting index and length of
the substring:
si
er

console.log(text.substr(7, 5)); // Output: "World"


m

Finding a Substring
Em

indexOf(): Returns the position of the first occurrence of a substring:

const text = 'Hello, World!';


console.log(text.indexOf('World')); // Output: 7

120
lastIndexOf(): Returns the position of the last occurrence of a substring:

const text = 'Hello, World, World!';


console.log(text.lastIndexOf('World')); // Output: 13

ng
includes(): Checks if a string contains a specific substring (returns true or
false):

ni
ar
const text = 'Hello, World!';
console.log(text.includes('World'));
Le // Output: true
ve
Replacing Substrings
replace(): Replaces the first occurrence of a substring with another string:
si

const text = 'Hello, World!';


er

const newText = text.replace('World', 'JavaScript');


console.log(newText); // Output: "Hello, JavaScript!"
m
Em

replaceAll(): Replaces all occurrences of a substring:

const text = 'Hello, World! World!';


const newText = text.replaceAll('World', 'JavaScript');
console.log(newText); // Output: "Hello, JavaScript!
JavaScript!"

121
Splitting a String
split(): Splits a string into an array based on a specified delimiter:

const text = 'apple,banana,cherry';

ng
const fruits = text.split(',');
console.log(fruits); // Output: ["apple", "banana", "cherry"]

ni
ar
4. String Comparisons
Le
Strings can be compared using comparison operators:
ve

===: Strict equality comparison:


si
er

console.log('apple' === 'apple'); // Output: true


console.log('apple' === 'Apple'); // Output: false
m
Em

>, <, >=, <=: Compare strings lexicographically (alphabetical order):

console.log('apple' > 'banana'); // Output: false

5. Escape Characters

122
Escape sequences are used to include special characters in strings:

● \n: New line


● \t: Tab
● \': Single quote
● \": Double quote

ng
● \\: Backslash

Example:

ni
const text = 'She said, \"Hello!\"';

ar
console.log(text); // Output: She said, "Hello!"

Le
ve
6. Multiline Strings

You can create multiline strings using backticks (template literals):


si
er

const multilineString = `This is a


multiline string`;
m

console.log(multilineString);
Em

Alternatively, you can use escape sequences in single or double quotes:

const multilineString = 'This is a \nmultiline string';


console.log(multilineString);

123
7. String Methods Summary

Here’s a quick summary of some commonly used string methods:

Method Description

length Returns the length of the string

ng
toUpperCase() Converts the string to uppercase

toLowerCase()

ni
Converts the string to lowercase

ar
indexOf() Finds the first occurrence of a substring

lastIndexOf() Finds the last occurrence of a substring

includes()
Le
Checks if a string contains a specific
substring
ve

slice() Extracts a section of a string


si

replace() Replaces a substring


er

split() Splits a string into an array


m
Em

8. Practice Problems

Here are some practice problems to help reinforce your understanding of strings:

1. Reverse a string: Write a function that takes a string as input and returns
the reversed string.

124
2. Count vowels: Write a function that counts the number of vowels in a
given string.
3. Palindrome check: Write a function that checks if a given string is a
palindrome (reads the same forward and backward).
4. Replace spaces: Write a function that replaces all spaces in a string with
-.

ng
ni
By understanding these basics, you will have a solid grasp of how to work with
strings in JavaScript.

ar
Le
9. JavaScript Date
ve

The Date object in JavaScript is used to handle dates and times. It provides a
si

way to work with date and time data, allowing you to get the current date, format
er

dates, manipulate dates, and more.


m
Em

125
ng
ni
ar
Le
Epoch ( Unix Epoch)
ve

The epoch is a reference point in time that is used as the starting point for a
si

particular time system. In other words, it’s the "zero point" from which time is
measured.
er

● For example:
m

○ In the context of the Unix time system (used in JavaScript and many
other programming languages), the epoch is January 1, 1970,
Em

00:00:00 (UTC).
○ This specific moment is used as the baseline for calculating time in
most systems.
○ Unix time counts the number of seconds (or milliseconds in some
cases) that have elapsed since this epoch.
○ Unix time is useful because it provides a consistent way to represent
time across different systems and platforms.

126
ng
ni
ar
Timestamps Le
● A timestamp in the Unix system is the number of seconds (or
ve
milliseconds) since the Unix epoch.

In JavaScript, the Date.now() method returns the number of milliseconds since


si

the Unix epoch.


er

const timestamp = Date.now(); // Current Unix timestamp in


m

milliseconds
console.log(timestamp); // Output: e.g., 1693047600000
Em

Example:

● Unix Epoch: January 1, 1970, 00:00:00 UTC


● Unix Timestamp: A number like 1693047600000 represents the number
of milliseconds since the Unix epoch.

127
Time Standards

The time standard is by which the world regulates clocks and time.

● UTC: Universal Coordinated Time (UTC) is the global standard for


timekeeping. It does not change with the seasons (unlike some local time
zones that adjust for daylight saving).

ng
● Time zone offsets: Most time zones are described in terms of their
difference from UTC (e.g., UTC+3, UTC-5).

ni
○ Example: UTC+1 (Central European Time) is one hour ahead of
UTC.

ar
Le
ve
si
er
m
Em

JavaScript and Time Zones

● By default, JavaScript works in the local time zone of the user's computer.
● The Date object provides several methods for working with both UTC and
local time.

128
1. Creating Date Objects

In JavaScript, there are several ways to create a Date object.

Using new Date()

ng
This will create a Date object representing the current date and time:

ni
const currentDate = new Date();
console.log(currentDate);

ar
Passing a Date String
Le
You can create a Date object from a date string:
ve
si

const specificDate = new Date("2024-08-26");


console.log(specificDate);
er
m

Passing Year, Month, Day, etc.


You can pass individual components like the year, month, day, hour, minute, etc.:
Em

const customDate = new Date(2024, 7, 26, 15, 30); // August 26,


2024, 15:30
console.log(customDate);

Note: Months are zero-indexed, meaning January is 0, February is 1, and so on.

129
2. Getting Date Information

JavaScript provides several methods to extract different parts of a date.

ng
ni
ar
Le
ve
si
er
m

Current Date and Time


Em

getFullYear(): Returns the year:

const currentDate = new Date();


console.log(currentDate.getFullYear()); // Output: 2024

130
getMonth(): Returns the month (0-11):

console.log(currentDate.getMonth()); // Output: 7 (August)

getDate(): Returns the day of the month (1-31):

ng
console.log(currentDate.getDate()); // Output: 26

ni
getDay(): Returns the day of the week (0-6, where 0 is Sunday):

ar
console.log(currentDate.getDay()); Le // Output: 1 (Monday)
ve

getHours(): Returns the hour (0-23):


si
er

console.log(currentDate.getHours()); // Output: 15
m

getMinutes(): Returns the minutes (0-59):


Em

console.log(currentDate.getMinutes()); // Output: 30

getSeconds(): Returns the seconds (0-59):

console.log(currentDate.getSeconds()); // Output: 0 (or another

131
value based on current time)

getMilliseconds(): Returns the milliseconds (0-999):

console.log(currentDate.getMilliseconds());

ng
ni
3. Setting Date and Time

ar
You can also change different parts of the date using setter methods.

Setting Year, Month, and Day


setFullYear(): Sets the year:
Le
ve

currentDate.setFullYear(2025);
si

console.log(currentDate);
er

setMonth(): Sets the month (0-11):


m
Em

currentDate.setMonth(11); // December

setDate(): Sets the day of the month:

currentDate.setDate(25);

132
Setting Hours, Minutes, and Seconds
setHours(): Sets the hour:

currentDate.setHours(14); // 2:00 PM

setMinutes(): Sets the minutes:

ng
ni
currentDate.setMinutes(45);

ar
setSeconds(): Sets the seconds:

currentDate.setSeconds(30);
Le
ve
si

4. Formatting Dates
er

JavaScript allows you to format dates using built-in methods.


m

Date to String Methods


toString(): Converts the Date object to a string:
Em

console.log(currentDate.toString()); // Output: "Mon Aug 26


2024 14:45:30 GMT+0000 (UTC)"

133
toDateString(): Returns only the date part as a string:

console.log(currentDate.toDateString()); // Output: "Mon Aug 26


2024"

toTimeString(): Returns only the time part as a string:

ng
ni
console.log(currentDate.toTimeString()); // Output: "14:45:30
GMT+0000 (UTC)"

ar
Le
toLocaleDateString(): Returns the date in a format specific to the locale:

console.log(currentDate.toLocaleDateString()); // Output:
ve

"8/26/2024" (depending on locale)


si

toLocaleTimeString(): Returns the time in a format specific to the locale:


er
m

console.log(currentDate.toLocaleTimeString()); // Output:
"2:45:30 PM" (depending on locale)
Em

5. Date Arithmetic (Adding/Subtracting Dates)

You can perform date arithmetic by manipulating the timestamp value.

Getting the Timestamp

134
The timestamp is the number of milliseconds since January 1, 1970 (Unix
Epoch).

const now = Date.now();


console.log(now); // Output: milliseconds since 1970

ng
Adding/Subtracting Days

ni
To add or subtract days, you can modify the date using the setDate() method:

ar
const futureDate = new Date();

console.log(futureDate);
Le
futureDate.setDate(futureDate.getDate() + 7); // Adds 7 days
ve

Difference Between Dates


si

You can subtract two dates to get the difference in milliseconds:


er

const date1 = new Date("2024-08-26");


m

const date2 = new Date("2024-09-01");


Em

const diff = date2 - date1;


console.log(diff / (1000 * 60 * 60 * 24)); // Difference in
days

6. JavaScript Date Methods Summary

135
Method Description

new Date() Creates a new Date object with current date


and time

getFullYear() Returns the year (4 digits)

getMonth() Returns the month (0-11)

ng
getDate() Returns the day of the month (1-31)

ni
getDay() Returns the day of the week (0-6, 0 is

ar
Sunday)

getHours() Returns the hour (0-23)

getMinutes()
Le
Returns the minutes (0-59)
ve
setFullYear() Sets the year

setMonth() Sets the month


si
er

setDate() Sets the day of the month

toDateString() Returns the date part as a string


m

toTimeString() Returns the time part as a string


Em

toLocaleDateString Returns the date in a locale-specific format

()

toLocaleTimeString Returns the time in a locale-specific format

()

136
7. Practice Problems

1. Display the current date and time using Date object methods.
2. Get the difference in days between two dates.
3. Add 10 days to the current date.
4. Find the day of the week of a specific date (e.g., your birthday).

ng
By understanding JavaScript’s Date object and its methods, you can efficiently

ni
handle date and time in various applications.

ar
10. JavaScript OOP Le
Object-Oriented Programming (OOP) is a programming paradigm centred
ve
around the concept of objects. These objects are instances of classes, which
define the blueprint for the data (properties) and methods (functions) they hold.
si

OOP allows for a more structured and modular approach to programming,


making it easier to manage and scale large applications.
er

In JavaScript, OOP is implemented using objects and prototypes. ES6


m

introduced a more traditional class-based syntax, but under the hood, JavaScript
remains a prototype-based language.
Em

Key Concepts of OOP in JavaScript

137
ng
ni
ar
Le
ve
si

1. Objects: The core of OOP, an object is a collection of key-value pairs


(properties and methods).
er

2. Classes: Blueprints for creating objects (introduced in ES6).


m

3. Constructor: A special method in a class for creating and initialising


objects.
Em

4. Inheritance: The mechanism by which one class can inherit properties and
methods from another.
5. Encapsulation: Restricting direct access to certain properties or methods,
and controlling how data is accessed or modified.
6. Polymorphism: The ability for different objects to be accessed through the
same interface, allowing for multiple forms of behaviour.

138
7. Abstraction: Simplifying complex systems by hiding the unnecessary
details and showing only essential features.

1. Objects in JavaScript

Objects are key to understanding OOP. In JavaScript, objects can be created

ng
using:

ni
ar
Le
ve
si
er
m
Em

Object Literals:

const person = {
name: "John",
age: 30,
greet: function() {

139
console.log("Hello, " + this.name);
}
};
person.greet(); // Output: Hello, John

Constructor Functions (before ES6 classes):

ng
function Person(name, age) {

ni
this.name = name;

ar
this.age = age;
this.greet = function() {

};
Le
console.log("Hello, " + this.name);

}
ve

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


si

john.greet(); // Output: Hello, John


er
m

ES6 Classes:
Em

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

140
greet() {
console.log("Hello, " + this.name);
}
}

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

ng
john.greet(); // Output: Hello, John

ni
ar
2. Classes and Constructors

Le
A class is a blueprint for creating objects. Classes contain properties and
methods. In JavaScript, the constructor method is used to initialise the object
when it's created using the new keyword.
ve

class Animal {
si

constructor(name, sound) {
er

this.name = name;
this.sound = sound;
m

}
Em

makeSound() {
console.log(this.name + " makes " + this.sound);
}
}

const dog = new Animal("Dog", "Bark");

141
dog.makeSound(); // Output: Dog makes Bark

3. Inheritance

Inheritance allows one class to inherit the properties and methods of another

ng
class. This is useful for code reuse and establishing relationships between
classes.

ni
ar
Le
ve
si
er
m
Em

Example of Inheritance:

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

142
makeSound() {
console.log(this.name + " makes a sound.");
}
}

ng
// Dog inherits from Animal
class Dog extends Animal {

ni
constructor(name, breed) {
super(name); // Call the parent constructor

ar
this.breed = breed;
}
Le
makeSound() {
ve
console.log(this.name + " barks.");
}
si

}
er

const dog = new Dog("Buddy", "Golden Retriever");


dog.makeSound(); // Output: Buddy barks.
m
Em

In this example, Dog inherits from Animal, but also overrides the makeSound
method.

4. Encapsulation

143
Encapsulation is the concept of restricting access to certain parts of an object.
This can be done using variables and methods inside a class but not allowing
them to be accessed from outside.

ng
ni
ar
Le
ve
In JavaScript, there's no direct way to create private variables (like in other OOP
languages), but closures or # prefix (introduced in ES2022) can be used to
si

achieve this.
er

Private Fields using #:


m
Em

class BankAccount {
#balance = 0;

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

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

ng
const account = new BankAccount();
account.deposit(100);

ni
console.log(account.getBalance()); // Output: 100

ar
In the example above, #balance is a private field that cannot be accessed or
Le
modified directly from outside the class.
ve

5. Polymorphism
si

Polymorphism allows different classes to be treated as instances of the same


er

class through inheritance. In JavaScript, this is achieved using method


overriding.
m
Em

145
ng
ni
ar
Le
Example of Polymorphism:
ve

class Animal {
si

makeSound() {
er

console.log("Some generic animal sound");


}
m

}
Em

class Dog extends Animal {


makeSound() {
console.log("Bark");
}
}

146
class Cat extends Animal {
makeSound() {
console.log("Meow");
}
}

ng
const animals = [new Dog(), new Cat()];

ni
animals.forEach(animal => {
animal.makeSound();

ar
});
// Output:
// Bark
Le
// Meow
ve

In this example, both Dog and Cat inherit from Animal, but they each implement
si

their own version of the makeSound method. The animals array contains
er

instances of both Dog and Cat, and the correct method is called for each object.
m
Em

6. Abstraction

Abstraction in JavaScript can be achieved by hiding unnecessary details and


exposing only the necessary parts of an object. It helps simplify complex code by
focusing only on what is relevant for the user of the object.

147
JavaScript does not have built-in support for abstract classes (like some other
languages), but we can simulate abstraction by creating classes with methods
that must be overridden.

Example of Abstraction:

ng
class Shape {
constructor() {
if (this.constructor === Shape) {

ni
throw new Error("Cannot instantiate abstract class");

ar
}
}

getArea() {
Le
throw new Error("Method 'getArea()' must be implemented.");
ve

}
}
si
er

class Circle extends Shape {


constructor(radius) {
m

super();
this.radius = radius;
Em

getArea() {
return Math.PI * this.radius * this.radius;
}
}

148
const circle = new Circle(5);
console.log(circle.getArea()); // Output: 78.53981633974483

In this example, Shape is an abstract class that defines a method getArea

ng
which is meant to be overridden by subclasses like Circle. Attempting to
instantiate Shape directly or call getArea without overriding would result in an

ni
error.

ar
Conclusion Le
JavaScript supports the four pillars of OOP: Encapsulation, Abstraction,
ve
Inheritance, and Polymorphism. With the introduction of classes in ES6, OOP
in JavaScript became more intuitive and aligned with OOP practices in other
programming languages. Understanding these concepts is critical to writing
si

well-structured, maintainable code, especially in large applications.


er
m
Em

11. Document Object Model.


The Document Object Model (DOM) is a programming interface for HTML and
XML documents. It represents the page so that programs can change the

149
document structure, style, and content. JavaScript can interact with the DOM to
manipulate web pages dynamically.

ng
ni
ar
Le
ve
si
er
m
Em

150
ng
ni
ar
What is the DOM?
Le
ve
● The DOM treats an HTML document as a tree structure, where each
element is an object. You can access and manipulate these objects with
si

JavaScript.
er

For example, in the HTML code:


m

<html>
Em

<body>
<h1>Hello, World!</h1>
<p>This is a paragraph.</p>
</body>
</html>

The DOM represents this as a tree:

151
html
├── body
├── h1
└── p

Using JavaScript, you can manipulate this structure to dynamically add, remove,

ng
or modify content on the web page.

ni
ar
Le
ve
si
er

Accessing the DOM


m
Em

152
ng
ni
ar
Le
ve

The first step in manipulating the DOM is to select the elements you want to
si

work with. JavaScript provides several methods to access these elements:


er
m
Em

153
ng
ni
ar
1. getElementById()
Le
ve
si
er
m
Em

154
○ Selects an element by its ID.

const element = document.getElementById('myId');

2. getElementsByClassName()
○ Selects all elements with a specific class name. Returns a collection

ng
(array-like object).

ni
const elements =
document.getElementsByClassName('myClass');

ar
3. getElementsByTagName()
Le
○ Selects all elements with a specific tag name (like div, p, h1, etc.).
ve

const elements = document.getElementsByTagName('p');


si
er

4. querySelector()
m

○ Selects the first element that matches a CSS selector (like #id,
Em

.class, tag).

const element = document.querySelector('#myId');

5. querySelectorAll()
○ Selects all elements that match a CSS selector. Returns a NodeList.

155
const elements = document.querySelectorAll('.myClass');

ng
ni
ar
Manipulating the DOM

Le
Once you've selected elements, you can manipulate them, such as changing
their content, style, or attributes.

1. Changing Content:
ve

○ You can modify the inner HTML of an element using the


innerHTML property.
si
er

const element = document.getElementById('myId');


element.innerHTML = "New Content!";
m
Em

2. Changing Styles:
○ You can update the CSS styles of an element using the style
property.

const element = document.querySelector('.myClass');

156
element.style.color = "red";
element.style.fontSize = "20px";

3. Changing Attributes:
○ You can modify the attributes of an element using the

ng
setAttribute() method.

ni
const element = document.querySelector('img');
element.setAttribute('src', 'newImage.jpg');

ar
4. Adding and Removing Classes:
Le
○ Use classList to add, remove, or toggle classes on elements.
ve

const element = document.querySelector('.myClass');


si

element.classList.add('newClass');
element.classList.remove('oldClass');
er

element.classList.toggle('active');
m
Em

Creating and Deleting Elements

1. Creating Elements:
○ You can create new HTML elements dynamically using the
createElement() method.

157
const newElement = document.createElement('p');
newElement.textContent = "This is a new paragraph.";
document.body.appendChild(newElement);

2. Removing Elements:

ng
○ You can remove elements using the removeChild() or remove()
method.

ni
const element = document.getElementById('myId');

ar
element.remove();

Le
ve

Event Handling in the DOM


si

Events allow JavaScript to interact with user actions, such as clicking buttons,
er

typing, or hovering over elements. You can handle events using event listeners.

Adding an Event Listener:


m

Use addEventListener() to handle events like click, mouseover,


Em

keydown, etc.

const button = document.querySelector('button');


button.addEventListener('click', function() {
alert('Button clicked!');
});

158
1. Removing an Event Listener:
You can also remove event listeners when they're no longer needed.

function showAlert() {

ng
alert('Button clicked!');
}

ni
const button = document.querySelector('button');

ar
button.addEventListener('click', showAlert);

// Remove the event listener Le


button.removeEventListener('click', showAlert);
ve
si
er

Traversing the DOM

You can navigate between elements using different DOM properties:


m
Em

159
ng
ni
ar
Le
ve
parentNode: Get the parent of an element.
si

const child = document.querySelector('p');


er

const parent = child.parentNode;


m
Em

children: Get all child elements of a specific element.

const parent = document.querySelector('div');


const children = parent.children;

160
nextElementSibling and previousElementSibling: Navigate to the next
or previous sibling element.

const current = document.querySelector('p');


const next = current.nextElementSibling;
const prev = current.previousElementSibling;

ng
ni
firstElementChild and lastElementChild: Access the first and last child

ar
of an element.

Le
const parent = document.querySelector('ul');
const first = parent.firstElementChild;
ve
const last = parent.lastElementChild.
si
er
m
Em

Example: A Simple DOM Manipulation

161
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>

ng
<h1 id="heading">Welcome!</h1>

ni
<button id="changeBtn">Change Heading</button>

ar
<script>

Le
const button = document.getElementById('changeBtn');

button.addEventListener('click', function() {
ve
const heading = document.getElementById('heading');
heading.textContent = "Hello, JavaScript!";
si

heading.style.color = "blue";
});
er

</script>
m

</body>
Em

</html>

In this example:

● When the button is clicked, the h1 element’s text and color are updated
using JavaScript.

162
Conclusion

JavaScript's interaction with the DOM allows developers to create dynamic and
interactive web pages. By understanding how to access and manipulate DOM
elements, handle events, and traverse the DOM tree, you can significantly

ng
enhance user experiences on the web.

Would you like to try a DOM-based project, or dive deeper into any specific

ni
aspect of the DOM?

ar
DOP Properties and Methods List. Le
In JavaScript, the DOM (Document Object Model) provides a wide range of
ve

properties and methods that allow you to interact with HTML and XML
documents. Here’s an overview of the most important DOM properties and
si

methods:
er
m

Common DOM Properties


Em

1. document

● Represents the whole web page.


● Example: document.title gets or sets the title of the document.

2. document.body

● Refers to the <body> element of the HTML document.

163
● Example: document.body.innerHTML gets or sets the HTML inside the
body.

3. document.head

● Refers to the <head> section of the document.


● Example: document.head.querySelector('meta') selects the first

ng
<meta> tag.

ni
4. element.id

ar
● Gets or sets the id of an element.
● Example: document.getElementById('myId').id = 'newId'.

5. element.className
Le
ve
● Gets or sets the class attribute of an element.
● Example: document.querySelector('div').className =
si

'newClass'.
er

6. element.classList
m

● Returns a DOMTokenList of the element’s classes.


● Example: element.classList.add('active').
Em

7. element.tagName

● Returns the tag name of an element in uppercase.


● Example: document.querySelector('p').tagName would return
'P'.

164
8. element.innerHTML

● Gets or sets the HTML content inside an element.


● Example: document.getElementById('myDiv').innerHTML =
'<p>Hello World</p>'.

9. element.textContent

ng
● Gets or sets the text content inside an element (ignores HTML tags).

ni
● Example: document.querySelector('h1').textContent = 'New
Heading'.

ar
10. element.style
Le
● Allows you to manipulate the CSS styles of an element.
● Example: element.style.color = 'red'.
ve

11. element.attributes
si

● Returns a NamedNodeMap of the attributes of an element.


er

● Example: element.attributes['class'].value would give the


value of the class attribute.
m

12. element.childNodes
Em

● Returns a NodeList of all child nodes, including text and comment nodes.
● Example: element.childNodes[0] gives the first child node.

13. element.children

165
● Returns an HTMLCollection of child elements (only elements, no text or
comment nodes).
● Example: element.children[1] gives the second child element.

14. element.firstElementChild and element.lastElementChild

● Returns the first and last child element of a parent.

ng
● Example: parent.firstElementChild gives the first child element.

ni
15. element.parentNode

ar
● Returns the parent node of the current element.
● Example: element.parentNode returns the parent element of element.

16. element.previousElementSibling and


Le
element.nextElementSibling
ve

● Returns the previous or next sibling element of the current element.


● Example: element.nextElementSibling returns the next sibling of
si

element.
er

17. element.innerHTML
m

● Gets or sets the HTML content inside an element.


Em

● Example: element.innerHTML = "<p>New Content</p>".

18. element.nodeName and element.nodeType

● nodeName: The name of the node (e.g., DIV, P).


● nodeType: The type of node (1 = Element, 3 = Text, etc.).
● Example: element.nodeName might return DIV.

166
Common DOM Methods

1. getElementById()

● Selects an element by its id.

ng
● Example: document.getElementById('myId').

2. getElementsByClassName()

ni
● Selects all elements with a specific class name (returns an

ar
HTMLCollection).

Le
● Example: document.getElementsByClassName('myClass').

3. getElementsByTagName()
ve
● Selects all elements with a specific tag name (returns an
HTMLCollection).
si

● Example: document.getElementsByTagName('div').
er

4. querySelector()
m

● Selects the first element that matches a CSS selector.


Em

● Example: document.querySelector('div').

5. querySelectorAll()

● Selects all elements that match a CSS selector (returns a NodeList).


● Example: document.querySelectorAll('.myClass').

6. createElement()

167
● Creates a new HTML element.
● Example: const newElement =
document.createElement('div').

7. createTextNode()

● Creates a new text node.

ng
● Example: const textNode = document.createTextNode('Hello
World').

ni
8. appendChild()

ar
● Appends a new child element or node to a parent element.
Le
● Example: document.body.appendChild(newElement).

9. removeChild()
ve

● Removes a child element from its parent.


● Example: parentElement.removeChild(childElement).
si
er

10. replaceChild()
m

● Replaces an existing child element with a new one.


● Example: parentElement.replaceChild(newElement,
Em

oldElement).

11. setAttribute()

● Sets the value of an attribute on an element.


● Example: element.setAttribute('src', 'image.jpg').

12. getAttribute()

168
● Gets the value of an attribute.
● Example: element.getAttribute('href').

13. removeAttribute()

● Removes an attribute from an element.


● Example: element.removeAttribute('class').

ng
14. addEventListener()

ni
● Attaches an event handler function to an element.

ar
Example:

Le
element.addEventListener('click', function() {
ve
alert('Element clicked');
});
si
er

15. removeEventListener()
m

● Removes an event listener from an element.


Em

● Example: element.removeEventListener('click',
handleClick).

16. cloneNode()

● Clones an element. You can optionally deep-clone it (including all child


elements).

169
● Example: const clone = element.cloneNode(true).

17. insertBefore()

● Inserts a new node before an existing node as a child of a specified parent.


● Example: parent.insertBefore(newElement,
existingElement).

ng
18. scrollIntoView()

ni
● Scrolls the element into view.

ar
● Example: element.scrollIntoView().

19. focus()

● Focuses on an input element.


Le
● Example: inputElement.focus().
ve

20. blur()
si

● Removes focus from an input element.


er

● Example: inputElement.blur().
m
Em

Node Properties and Methods

In addition to element-specific properties and methods, there are general Node


properties and methods that apply to all DOM nodes (elements, text nodes,
comments, etc.):

1. nodeName: Returns the name of the node (tag name for elements).

170
2. nodeType: Returns the type of the node (1 for elements, 3 for text nodes).
3. nodeValue: Gets or sets the value of a text node or attribute.
4. appendChild(): Adds a node as the last child of a parent.
5. removeChild(): Removes a child node from the DOM.
6. cloneNode(): Creates a copy of the node (shallow or deep).

ng
Example: Using DOM Properties and Methods

ni
Here’s a practical example to demonstrate some common DOM properties and

ar
methods:

<!DOCTYPE html>
<html>
Le
ve
<head>
<title>DOM Manipulation Example</title>
si

</head>
<body>
er

<h1 id="mainHeading">Hello World!</h1>


m

<button id="changeText">Change Text</button>


Em

<script>
// Select the button
const button = document.getElementById('changeText');

// Add event listener to the button


button.addEventListener('click', function() {

171
// Select the heading element
const heading = document.getElementById('mainHeading');

// Change its text content


heading.textContent = 'JavaScript is awesome!';

ng
// Change its style
heading.style.color = 'blue';

ni
heading.style.fontSize = '24px';
});

ar
</script>

</body>
Le
</html>
ve

● This example shows how to select elements, modify their content, and
si

handle an event.
er

12. Events.
m
Em

In JavaScript, events are actions or occurrences that happen in the browser, like
when a user clicks a button, types in a field, or scrolls a page. JavaScript can
listen for these events and react to them using event handlers or event
listeners.

172
ng
ni
ar
Common JavaScript Events
Le
ve
Here are some of the most commonly used events:

1. Mouse Events:
si

○ click: Fired when an element is clicked.


er

○ dblclick: Fired when an element is double-clicked.


○ mousedown: Fired when a mouse button is pressed down.
m

○ mouseup: Fired when a mouse button is released.


Em

○ mouseenter: Fired when the mouse pointer moves over an


element.
○ mouseleave: Fired when the mouse pointer leaves an element.
○ mousemove: Fired when the mouse moves within an element.
○ mouseover: Fired when the mouse is over an element.
2. Keyboard Events:
○ keydown: Fired when a key is pressed down.

173
○ keyup: Fired when a key is released.
○ keypress: Fired when a key is pressed down (now mostly replaced
by keydown and keyup).
3. Form Events:
○ submit: Fired when a form is submitted.
○ change: Fired when the value of an input, select, or textarea

ng
changes.
○ focus: Fired when an element gains focus.

ni
○ blur: Fired when an element loses focus.

ar
○ input: Fired when the value of an input element changes (similar to
change, but fires for every change).
4. Window Events:
Le
○ load: Fired when the whole page (including images, scripts, etc.) is
ve
loaded.
○ scroll: Fired when the user scrolls the page or an element.
si

○ resize: Fired when the browser window is resized.


5. Touch Events (for mobile):
er

○ touchstart: Fired when a touch point is placed on the screen.


m

○ touchmove: Fired when a touch point is moved across the screen.


○ touchend: Fired when a touch point is removed from the screen.
Em

174
ng
ni
ar
Le
ve
si
er

Event Handling
m
Em

Handling events in JavaScript involves setting up functions (called event


handlers) that will run when a particular event occurs. You can handle events in
several ways, including by using inline event handlers, event properties, and
the preferred method, event listeners.

175
ng
ni
ar
Le
ve
si
er
m

Ways to Handle Events in JavaScript


Em

176
ng
ni
ar
1. Inline Event Handlers
Le
You can add event handlers directly in the HTML by using event attributes like
ve

onclick, onmouseover, etc. However, this method is generally not


recommended because it mixes HTML and JavaScript.
si
er

Example:

<!DOCTYPE html>
m

<html>
Em

<body>

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

</body>
</html>

177
● In this example, when the button is clicked, the inline JavaScript will trigger
an alert() showing "Button clicked!".

2. Event Properties

ng
You can define event handlers by assigning functions to properties like onclick,

ni
onmouseover, and so on. This method is better than inline handlers but has the

ar
downside of overwriting any previously assigned handlers.

Example:

<!DOCTYPE html>
Le
<html>
ve
<body>
si

<button id="myButton">Click Me</button>


er

<script>
m

const button = document.getElementById('myButton');


Em

// Handling the click event using event property


button.onclick = function() {
alert('Button clicked!');
};
</script>

178
</body>
</html>

● The onclick property is used to attach an event handler to the button.


This handler shows an alert when the button is clicked.

ng
ni
3. Event Listeners (Preferred Method)

ar
The addEventListener() method is the modern and preferred way to handle

Le
events in JavaScript. It allows multiple event listeners to be added to the same
element without overwriting each other.

Syntax:
ve

element.addEventListener(event, function, useCapture);


si
er

● event: The type of event (e.g., 'click', 'mouseover').


m

● function: The function to execute when the event occurs.


● useCapture: An optional boolean indicating the event flow phase (false
Em

by default, meaning bubbling phase).

Example:

<!DOCTYPE html>
<html>
<body>

179
<button id="myButton">Click Me</button>

<script>
const button = document.getElementById('myButton');

ng
// Handling the click event using event listener
button.addEventListener('click', function() {

ni
alert('Button clicked using addEventListener!');
});

ar
</script>

</body>
Le
</html>
ve
si

● The addEventListener() method attaches the event handler to the


er

button. When clicked, the button will trigger the alert.

Advantages of addEventListener():
m

1. Multiple event listeners: You can attach more than one event listener to
Em

an element.
2. Separation of concerns: It keeps JavaScript code separate from HTML,
making the code more readable and maintainable.
3. Control event flow: You can control whether the event should be handled
during the capturing or bubbling phase.

180
Removing Event Listeners

You can remove an event listener using the removeEventListener() method.

Example:

ng
function sayHello() {
alert('Hello!');

ni
}

ar
// Add an event listener
button.addEventListener('click', sayHello);

// Remove the event listener


Le
ve
button.removeEventListener('click', sayHello);
si
er

Event Object
m

When an event is triggered, an event object is created, which contains


information about the event, such as:
Em

● The element that triggered the event (target).


● The type of event (type).
● The position of the mouse (clientX, clientY), etc.

Example: Using the Event Object

181
<!DOCTYPE html>
<html>
<head>
<title>JS Events</title>
</head>
<body>

ng
<button id="myButton">Click me</button>

ni
<script>

ar
const button = document.getElementById('myButton');

Le
button.addEventListener('click', function(event) {
console.log('Event type:', event.type);
ve
console.log('Clicked element:', event.target);
});
si

</script>
er

</body>
</html>
m
Em

● In this example, the event object is logged to the console, displaying


information about the click event.

Event Propagation (Bubbling & Capturing)

182
JavaScript events propagate through the DOM in two phases:

ng
ni
ar
Le
ve

1. Capturing Phase: The event moves from the window down to the target
si

element.
er

2. Bubbling Phase: The event bubbles back up from the target element to
the window.
m

By default, events bubble up, but you can listen to the capturing phase by setting
Em

the third parameter of addEventListener() to true.

Example: Event Bubbling

<!DOCTYPE html>
<html>
<head>

183
<title>Event Bubbling</title>
</head>
<body>

<div id="parentDiv">
<button id="childButton">Click me</button>

ng
</div>

ni
<script>
const parentDiv = document.getElementById('parentDiv');

ar
const childButton = document.getElementById('childButton');

Le
parentDiv.addEventListener('click', function() {
alert('Parent div clicked');
ve
});
si

childButton.addEventListener('click', function(event) {
alert('Button clicked');
er

// Stop event bubbling


event.stopPropagation();
m

});
Em

</script>

</body>
</html>

184
● In this example, when the button is clicked, both the button and the parent
<div> receive the event (bubbling). The event.stopPropagation()
method stops the event from propagating to the parent.

Prevent Default Behavior

ng
Some events have default behaviors (e.g., a form submission reloads the page).
You can prevent this default behavior using event.preventDefault().

ni
Example: Prevent Form Submission

ar
<!DOCTYPE html>
<html>
<head>
Le
<title>Prevent Default</title>
ve

</head>
<body>
si
er

<form id="myForm">
<input type="text" placeholder="Enter name" />
m

<button type="submit">Submit</button>
</form>
Em

<script>
const form = document.getElementById('myForm');

form.addEventListener('submit', function(event) {
event.preventDefault(); // Prevent form submission

185
alert('Form submission prevented!');
});
</script>

</body>
</html>

ng
ni
Event Delegation

ar
Event delegation is a technique in which a single event listener is used on a
Le
parent element to manage events for its child elements. This is especially useful
when you have dynamically created elements.
ve
Example: Event Delegation

<!DOCTYPE html>
si

<html>
<head>
er

<title>Event Delegation</title>
m

</head>
<body>
Em

<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>

186
<script>
const list = document.getElementById('myList');

list.addEventListener('click', function(event) {
if (event.target.tagName === 'LI') {

ng
alert('List item clicked: ' + event.target.textContent);
}

ni
});
</script>

ar
</body>
</html>
Le
ve

● In this example, a single event listener is added to the <ul>. When any
<li> is clicked, the event is handled using event delegation.
si
er

Conclusion
m

JavaScript events allow you to create interactive web pages by responding to


Em

user actions like clicks, key presses, form submissions, and more. By mastering
events and event handling, you can create dynamic and engaging experiences
for users.

13. Browser Object Model


187
The Browser Object Model (BOM) in JavaScript refers to the objects provided
by the browser that allow interaction with the browser window outside the context
of the web page's document (which is handled by the DOM). BOM provides
methods and properties to interact with the browser's environment, like
manipulating the browser window, getting information about the browser, and
controlling certain behaviors of the browser.

ng
ni
ar
Le
ve
si
er

Key Objects in the BOM:


m
Em

188
ng
ni
ar
1. window
2. navigator
3. screen
Le
4. location
ve

5. history
6. timers (setTimeout, setInterval)
si
er

1. window Object
m

The window object is the global object for everything related to the browser. All
Em

JavaScript code runs within the context of the window object. It contains
methods and properties to manipulate the browser window, such as opening new
windows, resizing, scrolling, and accessing other BOM objects.

Common window Properties and Methods:

189
● window.innerWidth / window.innerHeight: Get the width and height
of the browser's viewport.
● window.open(): Open a new browser window or tab.
● window.alert(): Display an alert dialog.
● window.prompt(): Display a dialog with a text input field.
● window.confirm(): Display a dialog with OK and Cancel buttons.

ng
● window.close(): Close the current browser window.
● window.scrollTo(): Scroll the browser window to a particular position.

ni
● window.resizeTo(): Resize the browser window.

ar
Example:

Le
// Get the width and height of the viewport
console.log(window.innerWidth); // Output: width of the
browser's content area
ve

console.log(window.innerHeight); // Output: height of the


browser's content area
si
er

// Open a new window


window.open('https://www.google.com', '_blank', 'width=600,
m

height=400');
Em

// Show an alert dialog


window.alert('Hello, BOM!');

2. navigator Object

190
The navigator object provides information about the browser and the system
running the browser. You can use it to detect the user's browser type, version,
platform, and more.

Common navigator Properties:

● navigator.userAgent: A string representing the browser's user agent

ng
(information about the browser and OS).
● navigator.language: The preferred language of the browser.

ni
● navigator.platform: The platform the browser is running on (e.g.,

ar
"Win32", "MacIntel").
● navigator.onLine: Boolean indicating whether the browser is online or
offline. Le
● navigator.geolocation: Access to the device's geolocation (latitude,
longitude).
ve

Example:
si

// Get browser's user agent


er

console.log(navigator.userAgent);
m

// Check if the browser is online


console.log(navigator.onLine); // Output: true or false
Em

// Get browser language


console.log(navigator.language); // e.g., "en-US"

3. screen Object

191
The screen object provides information about the user's display screen, such as
its width, height, and color depth.

Common screen Properties:

● screen.width: The width of the screen in pixels.


● screen.height: The height of the screen in pixels.

ng
● screen.availWidth: The width of the screen's available area (excluding
OS taskbars).

ni
● screen.availHeight: The height of the screen's available area.

ar
● screen.colorDepth: The number of bits used to display one color.

Example:

// Get the screen width and height


Le
console.log(screen.width); // Total screen width
ve
console.log(screen.height); // Total screen height
si

// Get available width and height (excluding UI elements like


er

taskbars)
console.log(screen.availWidth);
m

console.log(screen.availHeight);
Em

4. location Object

The location object provides information about the current URL of the browser
and allows you to manipulate the URL by redirecting to another page or reloading
the page.

192
Common location Properties and Methods:

● location.href: The full URL of the current page.


● location.protocol: The protocol used (e.g., "http:", "https:").
● location.host: The host (hostname and port) of the URL.
● location.pathname: The path of the URL (after the domain name).

ng
● location.search: The query string part of the URL (after ?).
● location.hash: The fragment identifier (after #).

ni
● location.assign(): Load a new document at the given URL.
● location.reload(): Reload the current page.

ar
● location.replace(): Replace the current document with a new one
(no back button). Le
Example:
ve
// Get the full URL of the page
console.log(location.href);
si
er

// Get just the domain and path


console.log(location.host);
m

console.log(location.pathname);
Em

// Reload the page


location.reload();

// Redirect to a new page


location.assign('https://www.example.com');

193
5. history Object

The history object allows you to interact with the browser's session history (the
pages visited in the current session). You can navigate forward and backward in
history or manipulate the history stack.

ng
Common history Methods:

ni
● history.back(): Navigate to the previous page.

ar
● history.forward(): Navigate to the next page.
● history.go(n): Go to a specific page in the history. A positive number
Le
moves forward, and a negative number moves backward.
● history.pushState(): Pushes a state onto the session history stack.
ve
● history.replaceState(): Modifies the current history entry.

Example:
si

// Go back to the previous page


er

history.back();
m

// Go forward to the next page


Em

history.forward();

// Go back two pages


history.go(-2);

194
6. JavaScript Timers: setTimeout and setInterval

JavaScript provides two important functions to handle timing in the browser:

● setTimeout(): Executes a function after a specified delay.


● setInterval(): Executes a function repeatedly with a fixed time delay
between executions.

ng
Example of setTimeout():

ni
// Execute the function after 3 seconds

ar
setTimeout(function() {
console.log('This message is displayed after 3 seconds');
}, 3000);
Le
ve
Example of setInterval():

// Execute the function every 2 seconds


si

setInterval(function() {
er

console.log('This message is displayed every 2 seconds');


}, 2000);
m
Em

You can also use clearTimeout() or clearInterval() to cancel the


timeout or interval.

BOM and its Role in Web Development

195
The BOM allows developers to interact with the browser beyond just the
document content. With BOM, you can:

● Access and control browser-specific properties like location, history, and


screen.
● Handle browser-related operations, such as opening or resizing windows.
● Work with browser history and perform page redirections.

ng
● Access device information and interact with the user’s geolocation.

While the DOM (Document Object Model) manipulates the structure and content

ni
of the page, the BOM interacts with the browser’s environment, making it

ar
essential for creating interactive, browser-aware applications.

Le
ve

14. Web Storage


si
er

JavaScript provides two types of web storage mechanisms: Local Storage and
Session Storage. These allow you to store data in the user's browser and
m

retrieve it later. Unlike cookies, web storage data is not sent to the server with
Em

each HTTP request, which makes it more efficient for certain use cases.

196
ng
ni
1. Local Storage

ar
Local Storage is used to store data with no expiration time. The data persists
Le
even after the browser is closed and reopened.

Key Points:
ve

● Data is stored on the client-side.


si

● Data persists until explicitly deleted.


● The storage limit is around 5-10 MB depending on the browser.
er

Common Methods:
m

● localStorage.setItem(key, value): Store a value with a specific


Em

key.
● localStorage.getItem(key): Retrieve a value using its key.
● localStorage.removeItem(key): Remove a specific item.
● localStorage.clear(): Clear all items stored.

Example:

197
// Storing data in Local Storage
localStorage.setItem('username', 'JohnDoe');

// Retrieving data from Local Storage


let username = localStorage.getItem('username');
console.log(username); // Output: JohnDoe

ng
// Removing a specific item from Local Storage

ni
localStorage.removeItem('username');

ar
// Clearing all data from Local Storage
localStorage.clear();
Le
2. Session Storage
ve

Session Storage is similar to Local Storage, but the data is stored only for the
si

duration of the page session. Once the browser (or tab) is closed, the data is
er

deleted.

Key Points:
m

● Data is stored on the client-side.


Em

● Data lasts until the browser or tab is closed.


● The storage limit is around 5MB, depending on the browser.

Common Methods:

● sessionStorage.setItem(key, value): Store a value with a


specific key.

198
● sessionStorage.getItem(key): Retrieve a value using its key.
● sessionStorage.removeItem(key): Remove a specific item.
● sessionStorage.clear(): Clear all items stored in the session.

Example:

// Storing data in Session Storage

ng
sessionStorage.setItem('sessionUser', 'JaneDoe');

ni
// Retrieving data from Session Storage
let sessionUser = sessionStorage.getItem('sessionUser');

ar
console.log(sessionUser); // Output: JaneDoe

Le
// Removing a specific item from Session Storage
sessionStorage.removeItem('sessionUser');
ve

// Clearing all data from Session Storage


si

sessionStorage.clear();
er
m

3. Differences Between Local Storage and Session Storage


Em

Feature Local Storage Session Storage

Data Data persists even after the Data is cleared when the tab
Persistenc browser is closed. or browser is closed.
e

199
Storage Around 5-10MB Around 5MB
Limit (browser-dependent). (browser-dependent).

Usage Ideal for storing long-term data Ideal for storing temporary
like user preferences or settings. data like session-specific info.

ng
4. Storage Data Type and Conversion

ni
Web storage only stores data in string format. If you need to store objects or

ar
arrays, you must convert them to a string using JSON.stringify(). When
retrieving, you should convert the string back to its original form using
JSON.parse(). Le
Example:
ve
// Storing an object in Local Storage
let user = {
si

name: 'John',
er

age: 30
};
m

localStorage.setItem('user', JSON.stringify(user));
Em

// Retrieving the object from Local Storage


let storedUser = JSON.parse(localStorage.getItem('user'));
console.log(storedUser.name); // Output: John
console.log(storedUser.age); // Output: 30

200
5. Web Storage Events

You can listen for changes in web storage using the storage event, which is
triggered whenever there is a change in the storage area (Local or Session
Storage). This is particularly useful when working with multiple tabs or windows.

ng
Example:

ni
window.addEventListener('storage', function(event) {
console.log('Key changed: ' + event.key);

ar
console.log('Old value: ' + event.oldValue);
console.log('New value: ' + event.newValue);

});
Le
console.log('Storage area: ' + event.storageArea);
ve
si

Use Cases for Web Storage:


er

● Storing user preferences (e.g., theme selection).


m

● Storing form data temporarily.


● Keeping track of user sessions or authentication tokens.
Em

● Saving game progress or app state across sessions.

201
Cookies

Cookies are another way to store data in the browser, but unlike Web Storage
(Local Storage and Session Storage), cookies are sent along with every HTTP
request to the server. This makes cookies useful for tracking user sessions,
authentication, and other server-side needs.

ng
What Are Cookies?

ni
● Cookies are small text files that store key-value pairs.
● They are used to store small amounts of data (up to 4KB) on the

ar
client-side.
● Cookies are sent to the server with every HTTP request, making them
Le
ideal for server-client communication, especially for maintaining sessions.

Structure of a Cookie
ve

A cookie consists of the following:


si

● Name: The name of the cookie.


er

● Value: The value associated with the cookie.


● Expiry date (optional): The expiration date after which the cookie will be
m

deleted.
● Domain and path (optional): The domain and path where the cookie is
Em

accessible.
● Secure flag (optional): The cookie is only sent over secure (HTTPS)
connections.
● HttpOnly flag (optional): The cookie cannot be accessed via JavaScript
(increases security).

Example of a Cookie

202
username=JohnDoe; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/;
domain=example.com; secure; HttpOnly

Managing Cookies in JavaScript

ng
1. Setting a Cookie

ni
You can set a cookie in JavaScript by assigning a string to document.cookie.

ar
// Set a cookie
document.cookie = "username=JohnDoe";
Le
To set an expiration date, domain, or path:
ve

// Set a cookie with expiration date and path


si

document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024


er

12:00:00 UTC; path=/";


m

2. Reading a Cookie
Em

You can read cookies using document.cookie, which returns all cookies as a
single string.

// Get all cookies


console.log(document.cookie);
// Output: "username=JohnDoe; theme=dark"

203
To read a specific cookie, you'll need to parse the string manually.

Example: Reading a specific cookie

function getCookie(name) {
let cookies = document.cookie.split(';');

ng
for (let i = 0; i < cookies.length; i++) {
let cookie = cookies[i].trim();

ni
if (cookie.indexOf(name + "=") === 0) {
return cookie.substring(name.length + 1);

ar
}
}
return null;
Le
}
ve

console.log(getCookie("username")); // Output: "JohnDoe"


si
er

3. Updating a Cookie
m

To update a cookie, you simply overwrite the cookie with the same name:
Em

// Update the cookie


document.cookie = "username=JaneDoe; expires=Fri, 31 Dec 2024
12:00:00 UTC; path=/";

4. Deleting a Cookie

To delete a cookie, set its expiration date to a past time:

204
// Delete the cookie by setting an expired date
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00
UTC; path=/";

ng
Cookie Attributes
expires: Sets an expiration date for the cookie. After this date, the cookie will be

ni
automatically deleted by the browser.

ar
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024
12:00:00 UTC"; Le
1. max-age: Similar to expires, but specifies the lifetime of the cookie in
ve
seconds.
si

document.cookie = "username=JohnDoe;
max-age=3600"; // Cookie lasts for 1 hour
er

2. path: Specifies the path for which the cookie is valid. The cookie will only
m

be sent for requests to that path and its subdirectories.


Em

document.cookie = "username=JohnDoe; path=/dashboard";

3. domain: Specifies the domain for which the cookie is valid.

205
document.cookie = "username=JohnDoe; domain=example.com";

4. secure: The cookie will only be sent over secure (HTTPS) connections.

document.cookie = "username=JohnDoe; secure";

5. HttpOnly: The cookie cannot be accessed via JavaScript, providing

ng
protection against cross-site scripting (XSS) attacks.

ni
document.cookie = "username=JohnDoe; HttpOnly";

ar
Cookies vs Web Storage
Le
ve
Feature Cookies Web Storage

Size Limit 4KB 5-10MB


si

Expiry Can be set manually or use Local Storage: persists until deleted, Session
er

session expiry Storage: deleted on tab close


m

Accessibility Sent with every HTTP Only accessible via JavaScript


request to the server
Em

Secure Can be made secure via Data is stored on the client and not sent with
secure and HttpOnly flags requests

Storage Type Stores small data for Larger data for client-side operations
server-side operations

206
Use Cases of Cookies

1. User Authentication: Storing session IDs to maintain login sessions.


2. Tracking User Behavior: Cookies can be used to track user activity
across pages.
3. Remembering User Preferences: Store settings like theme preferences
or language choices.

ng
4. Cross-Page State Sharing: Share state between different pages of a
website.

ni
ar
Conclusion
Le
Cookies are useful for storing small amounts of data that need to be sent to the
server, especially for maintaining user sessions and tracking. For larger amounts
ve
of client-side data, Web Storage (Local Storage and Session Storage) is more
efficient since the data is not sent with every request. However, cookies are
si

essential for server-side tasks such as authentication and maintaining user


sessions.
er
m
Em

207
Comparison of the three

ng
ni
ar
Le
That is all about Storages.
ve

15. Asynchronous
si
er

Programming
m
Em

Synchronous vs Asynchronous

In JavaScript, the main thread runs code synchronously (one line after the other).
However, some tasks, like network requests, can take time. Instead of making
the user wait, JavaScript uses asynchronous techniques to handle these tasks in
the background and continues executing other code..

208
ng
ni
ar
Le
1. Understanding Asynchronous Programming
ve
Asynchronous programming in JavaScript is a powerful paradigm that allows
tasks to be executed without blocking the main thread. Long-running tasks like
si

fetching data from an API or reading from a database can be performed without
freezing the entire program, making JavaScript highly efficient for web
er

development
m

Key Concepts:
Em

● Blocking: When a task prevents further execution until it's complete.


● Non-blocking: When a task is delegated, and the program can continue
executing other tasks.

JavaScript uses event loops and callbacks to manage asynchronous


operations, ensuring the program can perform multiple tasks without getting
blocked.

209
2. Callbacks

Callbacks are one of the earliest ways to handle asynchronous tasks. A callback
is a function passed as an argument to another function and is executed once a
task is completed.

Example:

ng
function fetchData(callback) {
setTimeout(() => {

ni
console.log("Data fetched");
callback();

ar
}, 2000); // Simulate an API call
}
Le
function processData() {
ve
console.log("Processing data");
}
si

fetchData(processData); // "Data fetched" will print first, then


er

"Processing data"
m
Em

● Issue with Callbacks: Callbacks can become difficult to manage,


especially when you have multiple levels of nested callbacks. This is
known as "Callback Hell".

210
ng
ni

ar
3. Promises
Le
Promises were introduced in ES6 to improve the way asynchronous operations
ve

are handled, making the code cleaner and more manageable than callbacks.
si

A promise represents the eventual completion (or failure) of an asynchronous


operation and its resulting value.
er

Promise States:
m

● Pending: The initial state, neither fulfilled nor rejected.


Em

● Fulfilled: The operation completed successfully.


● Rejected: The operation failed.

Creating a Promise:

let myPromise = new Promise(function(resolve, reject) {


let success = true; // Simulate success or failure
setTimeout(() => {

211
if (success) {
resolve("Data fetched successfully");
} else {
reject("Error fetching data");
}
}, 2000);

ng
});

ni
Using Promises (.then and .catch):

ar
myPromise
.then(result => {
Le
console.log(result); // Output: "Data fetched successfully"
})
ve
.catch(error => {
console.log(error); // If rejected, prints: "Error fetching
si

data"
});
er
m
Em

4. Chaining Promises

Promises allow chaining, where you can perform a series of asynchronous tasks
one after the other.

Example:

function fetchData() {

212
return new Promise((resolve) => {
setTimeout(() => resolve("Data fetched"), 2000);
});
}

function processData(data) {

ng
return new Promise((resolve) => {
setTimeout(() => resolve(data + " and processed"), 2000);

ni
});
}

ar
fetchData()
Le
.then(result => processData(result))
.then(finalResult => console.log(finalResult)) // Output:
ve
"Data fetched and processed"
.catch(error => console.log(error));
si
er

5. Async/Await
m

Async/Await was introduced in ES8 (ECMAScript 2017) and is built on top of


Em

promises. It provides a more readable and concise way to handle asynchronous


code.

async Keyword:

● When you declare a function as async, it automatically returns a promise.

await Keyword:

213
● The await keyword is used inside an async function to wait for a promise
to be resolved or rejected.

Example with async and await:

async function fetchData() {


return new Promise(resolve => {

ng
setTimeout(() => resolve("Data fetched"), 2000);
});

ni
}

ar
async function processData() {
const data = await fetchData(); // Wait for the data to be
fetched
console.log(data);
Le
// Output: "Data fetched"
ve
}

processData();
si
er

This makes asynchronous code look synchronous and easier to understand.


m

Example with Error Handling:


Em

You can use try...catch blocks to handle errors in async/await:

async function fetchData() {


return new Promise((resolve, reject) => {
let success = false;
setTimeout(() => {

214
if (success) {
resolve("Data fetched");
} else {
reject("Error fetching data");
}
}, 2000);

ng
});
}

ni
async function processData() {

ar
try {

Le
const data = await fetchData();
console.log(data);
} catch (error) {
ve
console.log(error); // Output: "Error fetching data"
}
si

}
er

processData();
m
Em

6. Asynchronous Operations in Practice

Common use cases for asynchronous programming:

1. Fetching Data from APIs: Using fetch() or AJAX to make HTTP


requests.
2. Timers: Using setTimeout and setInterval.

215
3. File Operations: Reading/writing files in environments like Node.js.
4. Event Handling: Handling user interactions asynchronously.

Example of Fetching Data:

async function getDataFromAPI() {


try {

ng
let response = await
fetch("https://jsonplaceholder.typicode.com/todos/1");
let data = await response.json();

ni
console.log(data); // Output: {userId: 1, id: 1, title:

ar
"delectus aut autem", completed: false}
} catch (error) {

}
console.log("Error:", error); Le
}
ve

getDataFromAPI();
si
er
m

7. Concurrency vs Parallelism
Em

● Concurrency: Multiple tasks are making progress at the same time (not
necessarily running at the same time).
● Parallelism: Multiple tasks are executed simultaneously.

JavaScript is single-threaded, meaning it can only execute one task at a time.


However, with asynchronous programming and the event loop, it achieves
concurrency by delegating tasks (like HTTP requests) to the browser, allowing
other code to execute while waiting for responses.

216
8. The Event Loop

The Event Loop is the core mechanism in JavaScript that allows asynchronous
code to be executed. It manages the call stack (where synchronous code is
executed) and the message queue (where asynchronous operations like

ng
promises or timers are queued).

● When the call stack is empty, the event loop checks the message queue

ni
and moves the first message to the call stack for execution.

ar
● This process allows JavaScript to handle asynchronous tasks while
maintaining a non-blocking environment.

Le
Conclusion
ve

Asynchronous programming in JavaScript is essential for handling long-running


si

tasks without blocking the main thread. Whether using callbacks, promises, or
the modern async/await syntax, understanding how JavaScript manages
er

asynchronous operations will improve your ability to write efficient, non-blocking


m

code.
Em

16. Network Request

217
JavaScript provides several ways to make network requests, which allow web
applications to communicate with servers, fetch data from APIs, send data, and
more.

ng
ni
ar
Le
The most commonly used methods for making network requests in modern
ve
JavaScript are:
si

1. XMLHttpRequest (old, but still used)


2. fetch API (modern, promise-based)
er

3. Third-party libraries (e.g., axios)


m

1. Using XMLHttpRequest
Em

XMLHttpRequest is the older way of making network requests in JavaScript.


While it is still supported in all browsers, it is more verbose compared to newer
methods like fetch.

Basic Example:

let xhr = new XMLHttpRequest();

218
xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1',
true);

xhr.onload = function() {
if (xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));

ng
} else {
console.log('Error:', xhr.status);

ni
}
};

ar
xhr.onerror = function() {
console.log('Request failed');
Le
};
ve

xhr.send();
si
er

● xhr.open sets up the request method (GET in this case) and the URL.
● xhr.onload is triggered when the request completes successfully.
m

● xhr.onerror handles any errors during the request.


Em

2. Using the fetch API

The fetch API is a more modern, promise-based approach to make network


requests and is widely used for its simplicity and ease of chaining.

219
Basic Example (GET request):

fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}

ng
return response.json(); // Parse the JSON from the response
})

ni
.then(data => console.log(data)) // Handle the response data
.catch(error => console.error('Error fetching data:', error));

ar
// Handle any errors

Le
● fetch returns a promise, which resolves when the request is complete.
ve
● response.ok checks if the request was successful (status in the range
200-299).
si

● .json() is used to parse the response as JSON.


● The .catch() block handles any errors.
er

Making a POST Request:


m

In a POST request, data is sent to the server. You can specify additional options
Em

like the method and body of the request.

fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'

220
},
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
})

ng
})
.then(response => response.json())

ni
.then(data => console.log(data)) // Handle the response
.catch(error => console.error('Error:', error));

ar
In this example: Le
● The method is set to 'POST'.
ve
● The headers define the request type as application/json.
● The body contains the data to be sent, which must be stringified using
si

JSON.stringify().
er

Example with Async/Await:


m

You can also use async/await syntax with fetch to make the code look more
Em

synchronous.

async function fetchData() {


try {
const response = await
fetch('https://jsonplaceholder.typicode.com/todos/1');
if (!response.ok) {

221
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);

ng
}
}

ni
fetchData();

ar
Le
This example uses async and await to simplify handling promises.
ve

3. Using Axios (Third-Party Library)


si

Axios is a popular third-party library that simplifies making HTTP requests in


er

JavaScript. It provides an easier syntax and automatic support for JSON.


m

Installing Axios:

npm install axios // If using Node.js or a build system


Em

Basic Example with Axios:

axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(response => {
console.log(response.data);

222
})
.catch(error => {
console.error('Error:', error);
});

ng
Making a POST Request with Axios:

axios.post('https://jsonplaceholder.typicode.com/posts', {

ni
title: 'foo',
body: 'bar',

ar
userId: 1
})
.then(response => {
Le
console.log(response.data);
ve
})
.catch(error => {
si

console.error('Error:', error);
});
er
m

Key Features of Axios:


Em

● Supports older browsers like Internet Explorer.


● Simplifies request/response handling.
● Automatically parses JSON.
● Allows request cancellation and timeouts.

223
4. Handling Response Data

When making a network request, you often need to work with the response data,
whether it's in JSON or another format. JavaScript provides ways to handle this
effectively.

● .json(): Converts the response to a JSON object.

ng
● .text(): Converts the response to plain text.

Example of Handling Text Data:

ni
fetch('https://example.com/some-text-file.txt')

ar
.then(response => response.text())
.then(data => console.log(data))
Le
.catch(error => console.error('Error:', error));
ve

5. Handling Errors
si
er

Always handle errors when making network requests. Errors can occur due to
network issues, server problems, or incorrect API usage.
m

● fetch treats HTTP errors (like 404 or 500) as successful responses, so


Em

you need to manually check response.ok.


● Try...catch is useful when using async/await for handling errors.

Example of Error Handling:

fetch('https://jsonplaceholder.typicode.com/invalid-url')

224
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})

ng
.catch(error => console.error('There was a problem with the
fetch operation:', error));

ni
ar
6. CORS (Cross-Origin Resource Sharing)
Le
When making requests from a browser to a different domain (cross-origin),
CORS policies apply. CORS ensures that only certain requests are allowed by
ve
the server to prevent security risks.
si

How to Handle CORS:


er

● If you're the server owner, ensure you set the appropriate CORS headers
to allow cross-origin requests.
m

● If you're fetching data from a third-party API, check if they allow CORS and
have set the proper headers.
Em

Conclusion

JavaScript provides multiple ways to make network requests:

● XMLHttpRequest: The old way of handling network requests.

225
● fetch: A modern and promise-based API for network requests, widely
supported in browsers.
● Axios: A third-party library that simplifies making HTTP requests and adds
additional features like interceptors and easier error handling.

By mastering these tools, you can easily interact with external servers, fetch
data, and send data to APIs in modern web development.

ng
ni
17. ES6+ New Features

ar
Le
ve
si
er
m
Em

ES6+ (ECMAScript 6 and beyond) Features in JavaScript

JavaScript underwent significant improvements with the release of ECMAScript 6


(ES6) and subsequent updates (ES7, ES8, etc.). These modern features make

226
JavaScript more powerful, concise, and easier to work with. Let's dive into some
of the most important ES6+ features:

1. Let and Const

In ES6, we have new ways to declare variables: let and const.

ng
● let: Declares a block-scoped variable (i.e., only available within the block

ni
{}).

ar
● const: Declares a block-scoped constant, which cannot be reassigned
after its initial assignment.

let x = 10; // can be reassigned


Le
const y = 20; // cannot be reassigned
ve

Differences:
si

● var is function-scoped, while let and const are block-scoped.


er

● Variables declared with const are immutable (cannot be reassigned).


m
Em

2. Arrow Functions

Arrow functions provide a more concise syntax for writing functions and
automatically bind this from the surrounding scope (lexical this).

// Traditional function
function greet(name) {

227
return `Hello, ${name}!`;
}

// Arrow function
const greet = (name) => `Hello, ${name}!`;

console.log(greet('John')); // Output: "Hello, John!"

ng
Key Features:

ni
● Implicit return: If there’s a single expression, no need for curly braces or

ar
the return keyword.
● No this binding: this refers to the surrounding lexical scope.
Le
ve
3. Template Literals

Template literals allow you to embed expressions in strings using backticks (`)
si

and ${} for interpolation.


er

const name = 'John';


m

const age = 25;


Em

const greeting = `Hello, my name is ${name} and I am ${age}


years old.`;
console.log(greeting); // Output: "Hello, my name is John and I
am 25 years old."

Benefits:

● Multiline strings without \n

228
● Expression interpolation for embedding variables

4. Default Parameters

You can now assign default values to function parameters if no value or


undefined is passed.

ng
function greet(name = 'Stranger') {

ni
return `Hello, ${name}!`;
}

ar
console.log(greet()); // Output: "Hello, Stranger!"
Le
console.log(greet('John')); // Output: "Hello, John!"
ve

5. Destructuring Assignment
si

Destructuring allows you to unpack values from arrays or properties from objects
er

into distinct variables.

Array Destructuring:
m

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


Em

console.log(a); // 10
console.log(b); // 20

Object Destructuring:

const person = { name: 'John', age: 25 };


const { name, age } = person;
console.log(name); // John

229
console.log(age); // 25

6. Rest and Spread Operators (...)

● Spread Operator: Expands an array or object into individual elements or

ng
properties.

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

ar
const obj1 = { a: 1, b: 2 };

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

● Rest Operator: Collects all remaining elements into an array.


ve

function sum(...numbers) {
si

return numbers.reduce((acc, num) => acc + num, 0);


}
er

console.log(sum(1, 2, 3)); // Output: 6


m
Em

7. Enhanced Object Literals

ES6 introduced a shorthand syntax for creating objects from variables and
defining methods.

const name = 'John';


const age = 25;

230
const person = {
name,
age,
greet() {
console.log(`Hello, my name is ${this.name}.`);
},
};

ng
person.greet(); // Output: "Hello, my name is John."

ni
ar
8. Promises
Le
Promises simplify asynchronous programming by providing a cleaner syntax for
handling async operations.
ve

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


setTimeout(() => resolve('Data fetched'), 1000);
si

});
er

fetchData
.then((result) => console.log(result)) // Output: "Data
m

fetched"
.catch((error) => console.error(error));
Em

Key Points:

● then() is called when the promise is resolved successfully.


● catch() handles any errors (rejection).

231
9. Classes

ES6 introduced classes, providing a cleaner, object-oriented approach to


JavaScript programming.

class Person {
constructor(name, age) {

ng
this.name = name;
this.age = age;
}

ni
greet() {

ar
console.log(`Hello, my name is ${this.name}.`);
}
}

const john = new Person('John', 25);


Le
john.greet(); // Output: "Hello, my name is John."
ve

Key Concepts:
si

● constructor method is used for initializing objects.


er

● Methods can be defined within the class.


m
Em

10. Modules (Import/Export)

JavaScript now supports native modules to break your code into separate files.

● Export: You can export variables, functions, or classes from a module.

// file: math.js

232
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;

● Import: You can import them into other files.

// file: app.js

ng
import { add, subtract } from './math.js';

console.log(add(2, 3)); // Output: 5

ni
console.log(subtract(5, 2)); // Output: 3

ar
11. Async/Await (ES8) Le
async and await provide an elegant way to handle asynchronous operations,
ve
making the code appear more synchronous.
si

async function fetchData() {


try {
er

const response = await


fetch('https://api.example.com/data');
m

const data = await response.json();


console.log(data);
Em

} catch (error) {
console.error('Error fetching data:', error);
}
}

fetchData();

Key Features:

233
● async functions automatically return a promise.
● await pauses the function execution until the promise is resolved.

12. Optional Chaining (ES11)

ng
Optional chaining allows you to safely access deeply nested object properties
without checking for null or undefined.

ni
const user = { name: 'John', address: { city: 'New York' } };

ar
console.log(user?.address?.city); // "New York"
console.log(user?.contact?.phone); // undefined (without
throwing an error) Le
ve

13. Nullish Coalescing Operator (??)


si

The ?? operator provides a default value when a variable is null or


er

undefined.
m

const value = null;


Em

const defaultValue = value ?? 'Default';


console.log(defaultValue); // Output: "Default"

Conclusion

234
ES6 and beyond introduced a plethora of features that made JavaScript more
powerful and developer-friendly. Mastering these features will enable you to write
cleaner, more efficient, and more maintainable JavaScript code.

18. JavaScript and Web Development

ng
Introduction to JavaScript and Web Development

ni
JavaScript is a versatile programming language that powers the dynamic

ar
behavior on most websites. Together with HTML (for structure) and CSS (for
styling), JavaScript forms the backbone of modern web development. Learning
Le
JavaScript is essential for creating interactive, responsive, and feature-rich
websites and applications.
ve
Let’s explore the role of JavaScript in web development and the key concepts
you need to understand to start building modern web applications.
si
er

The Role of JavaScript in Web Development


m

JavaScript is primarily used for:


Em

1. Interactivity: JavaScript enables users to interact with the web page, like
clicking buttons, submitting forms, hovering over elements, etc.
2. DOM Manipulation: JavaScript can modify the structure, content, and
style of a webpage by manipulating the Document Object Model (DOM).
3. API Communication: JavaScript allows you to send and receive data from
web servers via APIs using fetch() or XMLHttpRequest (Ajax).

235
4. Event Handling: JavaScript handles events like clicks, key presses, or
mouse movements.
5. Client-Side Validation: JavaScript can validate form inputs before sending
data to a server.

ng
Setting Up Your JavaScript Environment

To write and execute JavaScript for web development, you only need:

ni
● A web browser (most browsers like Chrome, Firefox, and Edge have

ar
JavaScript engines).
● A code editor like Visual Studio Code (VS Code) or Sublime Text.

Example HTML File with JavaScript:


Le
<!DOCTYPE html>
ve
<html lang="en">
<head>
si

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
er

initial-scale=1.0">
<title>JavaScript Web Development</title>
m

</head>
<body>
<h1>Welcome to JavaScript and Web Development</h1>
Em

<button onclick="showMessage()">Click Me</button>

<script>
function showMessage() {
alert('Hello, this is JavaScript in action!');
}
</script>
</body>

236
</html>

● HTML provides the structure, with a button in this case.


● JavaScript is embedded inside <script> tags to make the button
interactive. When clicked, the button triggers a pop-up alert message.

ng
JavaScript and the DOM (Document Object Model)

ni
ar
The DOM is a tree-like structure representing the elements of a webpage.
JavaScript interacts with the DOM to dynamically modify the content and
appearance of a page.

Accessing DOM Elements:


Le
ve
You can select and manipulate HTML elements using JavaScript. Some common
methods include:
si

● getElementById(): Selects an element by its ID.


er

● getElementsByClassName(): Selects elements by class name.


● querySelector(): Selects the first element that matches a CSS
m

selector.
Em

Example:

<p id="myText">Hello, World!</p>


<button onclick="changeText()">Change Text</button>

<script>
function changeText() {

237
document.getElementById("myText").innerText = "Text
Changed!";
}
</script>

When the button is clicked, JavaScript changes the paragraph's text from "Hello,

ng
World!" to "Text Changed!".

ni
JavaScript Events

ar
Events are actions that happen on a webpage (like clicking a button, scrolling, or
Le
typing). JavaScript can listen for these events and trigger specific functions when
they occur.
ve
Common Events:

● click: Fired when an element is clicked.


si

● input: Fired when a user types in an input field.


er

● mouseover: Fired when the mouse hovers over an element.


● submit: Fired when a form is submitted.
m

Event Listener Example:


Em

<button id="btn">Click Me</button>

<script>
const button = document.getElementById('btn');
button.addEventListener('click', function() {
alert('Button was clicked!');
});

238
</script>

Here, the addEventListener() method listens for a click event on the button
and shows an alert when clicked.

ng
Working with Forms in JavaScript

ni
JavaScript is essential for handling user inputs and validating forms before

ar
submitting data to the server.

Form Validation Example:

<form onsubmit="return validateForm()">


Le
Name: <input type="text" id="name"><br>
Email: <input type="text" id="email"><br>
ve
<input type="submit" value="Submit">
</form>
si

<script>
er

function validateForm() {
const name = document.getElementById('name').value;
m

const email = document.getElementById('email').value;

if (name === "" || email === "") {


Em

alert("Both name and email are required!");


return false;
}

return true; // form will submit


}
</script>

239
Before the form is submitted, JavaScript checks if the name and email fields are
filled out. If they are empty, it prevents submission and shows an alert.

JavaScript Fetch API for Network Requests

JavaScript can make network requests to APIs to send or fetch data without

ng
refreshing the page. The Fetch API is a modern way to handle network requests.

ni
Fetch API Example:

ar
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => console.log(data))
Le
.catch(error => console.error('Error:', error));
ve
This fetches data from an API and logs it to the console. The then() method is
used to handle the response, while catch() handles any errors.
si
er

JavaScript and Local Storage


m

Web Storage API allows you to store data in the browser that persists even after
Em

the page is refreshed. This is useful for storing user preferences, session
information, etc.

Using localStorage Example:

// Store data in local storage


localStorage.setItem('name', 'John Doe');

240
// Retrieve data from local storage
const name = localStorage.getItem('name');
console.log(name); // Output: John Doe

localStorage persists until explicitly deleted, while sessionStorage is


cleared when the page session ends.

ng
ni
JavaScript Frameworks and Libraries

ar
Once you're comfortable with JavaScript fundamentals, you can move on to
powerful JavaScript libraries and frameworks to simplify web development tasks:
Le
● jQuery: A lightweight library that simplifies DOM manipulation, event
handling, and animations.
ve
● React: A JavaScript library for building user interfaces, focusing on
reusable components and state management.
si

● Vue.js: A progressive framework for building user interfaces with an


approachable, versatile architecture.
er

● Angular: A full-fledged framework developed by Google for building


m

single-page applications (SPAs).


Em

Summary and Next Steps

JavaScript is a key player in making websites interactive, responsive, and


dynamic. By mastering JavaScript and its role in web development, you can build
highly interactive web applications. Here's a recap of what we've covered:

241
1. JavaScript Basics: Variables, operators, functions, and events.
2. DOM Manipulation: Access and modify HTML elements.
3. Forms and Validation: Handling user input and form validation.
4. Network Requests: Fetching data from APIs with fetch().
5. Web Storage: Storing data in the browser.
6. JavaScript Libraries and Frameworks: Tools for building modern web

ng
applications.

ni
19. Testing and Debugging in javaScript

ar
Testing and Debugging in JavaScript
Le
Testing and debugging are crucial aspects of JavaScript development, ensuring
that your code works correctly and is free from errors. Here, we will cover
ve
different types of testing, tools for debugging, and best practices for writing
reliable JavaScript code.
si
er

1. JavaScript Debugging
m

Debugging is the process of identifying and fixing errors in your code. The goal is
Em

to make sure that your program runs as expected without any bugs. Modern
browsers like Chrome, Firefox, and Edge have built-in developer tools that make
debugging JavaScript easy.

Common Debugging Techniques

242
● Using console.log(): This is the most basic form of debugging. By
inserting console.log() statements in your code, you can inspect
values and see how your program is executing.

const name = "John";


console.log(name); // Output: John

ng
ni
● Breakpoints in Developer Tools: Browsers like Chrome offer developer
tools where you can set breakpoints in your JavaScript code. A breakpoint

ar
pauses code execution at a specific line, allowing you to inspect variables
and step through your code.
To use breakpoints in Chrome:
Le
1. Right-click on the page and select Inspect.
ve
2. Go to the Sources tab.
3. Find your JavaScript file, click on a line number to set a breakpoint.
4. Run your script, and the browser will pause execution at that point.
si

● Error Handling with try-catch: You can use try-catch blocks to


er

handle errors gracefully. This prevents your code from crashing when an
error occurs.
m
Em

try {
nonExistentFunction(); // This will cause an error
} catch (error) {
console.error("An error occurred: ", error.message);
}

Debugging Tips

243
● Always check the Console for error messages and stack traces.
● Use Step Over and Step Into buttons in browser dev tools to navigate
through your code.
● Clear old console logs to focus on current issues.

ng
2. JavaScript Testing

Testing ensures your JavaScript code behaves as expected under different

ni
conditions. There are several types of testing approaches used in JavaScript

ar
development:

Types of JavaScript Testing


Le
1. Unit Testing: Testing individual units or functions to verify they work
correctly. Each test focuses on a small part of the code (e.g., a function).
ve
2. Integration Testing: Testing how different modules or components of your
application work together.
si

3. End-to-End (E2E) Testing: Simulating real user interactions in your


er

application, such as filling out forms or clicking buttons, to ensure


everything works as expected.
m

4. Regression Testing: Ensuring that new updates or features don't break


existing functionality.
Em

Common Testing Tools and Libraries

● Jest: A powerful JavaScript testing framework used for unit testing,


commonly used with React but also works with vanilla JavaScript.
● Mocha: A feature-rich JavaScript test framework running on Node.js and in
the browser.
● Chai: A TDD/BDD assertion library often used with Mocha.

244
● Cypress: A tool for end-to-end testing that runs in the browser, ideal for
testing web applications.
● QUnit: A JavaScript unit testing framework that’s easy to use and suitable
for any JS codebase.

ng
3. Unit Testing Example with Jest

Let's see an example of a unit test using Jest.

ni
Installation:

ar
First, you need to install Jest. If you're using Node.js, run the following command:

Bash code
Le
npm install --save-dev jest
ve

Writing a Test:
si

Here’s how you can write a simple unit test for a function using Jest:
er

// add.js - A simple function to add two numbers


m

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

module.exports = add;

// add.test.js - The test file for the add function


const add = require('./add');

test('adds 1 + 2 to equal 3', () => {

245
expect(add(1, 2)).toBe(3);
});

To run the test, add a script to your package.json:

Json code

ng
"scripts": {
"test": "jest"
}

ni
ar
Now, run the test using the following command:

Bash code

npm test
Le
ve

If everything works correctly, Jest will output that the test has passed.
si

More Advanced Unit Test:


er

You can also test for error handling, edge cases, or even asynchronous code:
m

// divide.js
function divide(a, b) {
Em

if (b === 0) throw new Error("Cannot divide by zero");


return a / b;
}

module.exports = divide;

// divide.test.js

246
const divide = require('./divide');

test('divides 6 by 2 to equal 3', () => {


expect(divide(6, 2)).toBe(3);
});

test('throws an error when dividing by zero', () => {


expect(() => divide(6, 0)).toThrow("Cannot divide by zero");

ng
});

ni
ar
4. End-to-End Testing Example with Cypress

Le
Cypress is ideal for testing how your JavaScript interacts with the user interface.

Installation:
ve
To install Cypress, use the following command:

Bash code
si

npm install cypress --save-dev


er
m

Writing an E2E Test:


Em

Here's an example of an end-to-end test for a simple to-do application using


Cypress:

describe('My First Test', function() {


it('Visits the To-Do App and adds a new task', function() {
// Visit the website
cy.visit('http://localhost:3000');

247
// Check if the input field is present and type a task
cy.get('.new-todo').type('Buy milk{enter}');

// Verify that the new task is added to the list


cy.contains('Buy milk').should('exist');
});
});

ng
To run the Cypress tests:

ni
Bash code

ar
npx cypress open

Le
This will open the Cypress test runner, where you can see the test execute in a
browser.
ve
si

5. Test-Driven Development (TDD)


er

Test-Driven Development (TDD) is a software development process where you


write tests before writing the actual code. TDD follows three steps:
m

1. Write a failing test.


Em

2. Write the minimum code required to pass the test.


3. Refactor the code to improve its structure, keeping the tests passing.

TDD ensures that your code is well-tested and designed from the start, reducing
the likelihood of bugs.

248
6. Debugging Tools

In addition to console.log() and browser developer tools, there are other


useful tools and techniques:

● Linting: Tools like ESLint analyze your code to find syntax errors and
potential bugs. It can catch issues before you even run the code.

ng
● Source Maps: Source maps allow you to debug minified or transpiled code
(like TypeScript or Babel-compiled JavaScript) by mapping it back to the

ni
original source code.
● Third-Party Debugging Tools:

ar
○ Sentry: A real-time error monitoring tool that helps track and fix
errors in production.
Le
○ Debugger Statements: You can insert debugger; into your code
to pause execution at that point.
ve
si

7. Best Practices for Testing and Debugging


er

● Write Tests Early: Try to write tests as you develop, rather than after the
code is finished. This helps catch bugs early.
m

● Test Small Units: Focus on unit testing individual functions or components


in isolation.
Em

● Automate Tests: Use CI/CD pipelines (e.g., GitHub Actions) to run tests
automatically when code is pushed to your repository.
● Modularize Your Code: Write small, reusable functions and modules that
are easier to test.
● Use Linting and Formatting Tools: Enforce consistent code style and
avoid errors with tools like ESLint and Prettier.

249
● Monitor Logs in Production: Use error tracking services (e.g., Sentry) to
catch issues after deployment.

Conclusion

Testing and debugging are essential to writing robust JavaScript applications. By

ng
mastering tools like Jest, Cypress, and browser dev tools, you'll improve your
ability to catch bugs early and ensure your code works as expected. Whether

ni
you're doing unit tests or end-to-end tests, consistent testing practices will save

ar
you time and prevent issues in the long run.

Next steps:
Le
● Write unit tests for your functions using Jest or Mocha.
● Set up Cypress for E2E testing in a small web project.
ve
● Practice debugging with the browser developer tools, using breakpoints
and the console effectively.
si
er
m
Em

That is All.

250
Thank you for joining me on this journey. Your time, curiosity, and dedication
mean the world to me. I hope this book has inspired you, expanded your
knowledge, and ignited your passion.

Keep learning, keep growing, and remember—great things are built one step at a

ng
time.

ni
For any message, feel free to reach out to me at: 0923191253

ar
Le
Happy creating, and until next time—stay curious and keep coding!

Happy Coding
ve
si
er

Muhammed Teshome
m
Em

251

You might also like