JavaScript HandBook
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:
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
Null)
Em
1
○ Defining and Calling Functions
○ Function Parameters and Return Values
○ Function Expressions and Arrow Functions
○ Scope and Closures
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 Interpolation
m
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
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
1. Browser APIs
Le
○ Introduction to Browser APIs
ve
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
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
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
7
1. What is JavaScript?
ng
ni
ar
Le
ve
si
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
● Google Chrome: V8
er
● 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
and Vue.js.
er
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
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
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.
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
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
14
they are initialized. However, if the constant is an object or array, the
properties or elements can be modified.
Example:
ng
const myConst = 30; // Block-scoped and immutable
ni
ar
Le
ve
si
er
● Variables must begin with a letter, underscore (_), or dollar sign ($).
Em
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
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
123456789012345678901234567890n;
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
18
6. Type Conversion
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:
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
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
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
1. Literal Expressions:
20
○ These are the simplest forms of expressions that directly represent
values.
Example:
Javascript code
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
3. Operator Expressions:
m
Example:
Javascript code
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
6. Logical Expressions:
○ These expressions use logical operators and evaluate to a boolean
value.
22
Example:
ng
○
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
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
24
Loops:
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
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:
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
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.
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
call)
}
27
JavaScript Operators
ng
ni
ar
Le
ve
si
JavaScript operators are special symbols or keywords that are used to perform
er
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
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
30
let product = 10 * 5; // 50
let quotient = 10 / 2; // 5
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
let a = 5;
a++; // a is now 6
m
●
Em
let b = 5;
b--; // b is now 4
31
2. Assignment Operators
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
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
36
4. Logical Operators
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
Copy code
true || false; // true
Em
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
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
●
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
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.
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
8. String Operators
41
Concatenation (+): Combines two strings.
javascript
Copy code
let greeting = "Hello, " + "World!";
console.log(greeting); // "Hello, World!"
ng
●
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
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
ng
ni
ar
Le
ve
si
er
1.1 if Statement
m
44
ng
ni
ar
Syntax:
Le
ve
if (condition) {
// code to be executed if the condition is true
si
}
er
Example:
m
Em
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
46
Example:
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
49
ng
ni
ar
Le
ve
si
Syntax:
er
m
switch (expression) {
case value1:
Em
50
// code to be executed if expression doesn't match any case
}
Example:
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
}
m
2. Looping Statements
Em
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
}
m
Em
53
Example:
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
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:
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
if (i === 5) {
m
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
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
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.
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".
60
function fizzBuzz(n) {
// Your code here
}
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
function isLeapYear(year) {
Em
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.
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.
function sumOfDigits(number) {
si
Problem 7: Factorial
Em
function factorial(n) {
// Your code here
}
62
Problem 8: Reverse a String
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
function countVowels(str) {
si
}
m
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.
function isPrime(n) {
// Your code here
}
63
Problem 11: Find the Largest Element in an Array
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
function isPalindrome(str) {
// Your code here
m
}
Em
Task: Write a function printPattern(n) that prints the following pattern for a
given n:
markdown
64
*
**
***
****
*****
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
Start here :
m
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
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
1. Defining a Function
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:
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
// code to be executed
}
Example:
72
function greet(name) {
console.log("Hello, " + name + "!");
}
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
}
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
};
m
Em
Example:
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
// code to be executed
};
Em
Example:
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
// code to be executed
}
Example:
76
function greet(name = "stranger") {
console.log("Hello, " + name + "!");
}
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
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
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.
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
Answer:
79
● Function Expression: A function expression is not hoisted, meaning it
cannot be called before it's assigned.
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
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:
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
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
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
};
}
83
8. IIFE (Immediately Invoked Function Expression)
Answer:
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
function repeatNTimes that takes a function and a number n, and calls the
given function n times.
Answer:
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
executed.
Em
Answer:
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
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
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.
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
console.log(person.name); // "Mehammed"
console.log(person['age']); // 27
m
Em
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
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
94
ng
ni
ar
Le
ve
● Object.keys(): Returns an array of the object’s keys (property names).
"country"]
er
m
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
console.log(myCar.year); // 2020
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
Example:
er
const user = {
m
name: "Alice",
age: 25,
Em
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
// 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
99
Questions to test your Understanding
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
Question: Given the object below, how do you access the city property using
Em
const user = {
name: "Mehammed",
city: "Addis Ababa",
age: 25
};
100
Answer:
Dot notation:
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
const person = {
m
name: "Mehammed",
age: 30
Em
};
Answer:
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" }
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:
// 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:
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
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
300]
Em
Question: What is the prototype of an object in JavaScript, and how can you add
a method to an object's prototype?
106
Answer:
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
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
Array constructor:
108
2. Accessing Array Elements
Array elements are accessed by their index. Indexes start from 0 (zero-based
index):
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
109
ng
ni
ar
Le
Here are some important array methods:
fruits.push("grape");
si
fruits.pop();
console.log(fruits); // Output: ["apple", "orange", "cherry"]
110
fruits.shift();
console.log(fruits); // Output: ["orange", "cherry"]
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
111
console.log(sliced); // Output: ["orange", "cherry"]
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
for loop:
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
113
7. 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
The spread operator (...) can be used to copy and merge arrays:
Copying an array:
114
Merging arrays:
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
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
116
Using backticks (Template literals): These are mainly used for string
interpolation and multi-line strings:
ng
ni
2. String Interpolation (Template Literals)
ar
Template literals (backticks) allow you to embed expressions inside a string using
${}:
117
ng
ni
ar
Le
ve
si
String Length
er
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
Or using concat():
119
Doe"
Extracting a Substring
slice(): Extracts part of a string based on the given start and end indexes:
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:
Finding a Substring
Em
120
lastIndexOf(): Returns the position of the last occurrence of a substring:
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
121
Splitting a String
split(): Splits a string into an array based on a specified delimiter:
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
5. Escape Characters
122
Escape sequences are used to include special characters in strings:
ng
● \\: Backslash
Example:
ni
const text = 'She said, \"Hello!\"';
ar
console.log(text); // Output: She said, "Hello!"
Le
ve
6. Multiline Strings
console.log(multilineString);
Em
123
7. String Methods Summary
Method Description
ng
toUpperCase() Converts the string to uppercase
toLowerCase()
ni
Converts the string to lowercase
ar
indexOf() Finds the first occurrence of a substring
includes()
Le
Checks if a string contains a specific
substring
ve
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
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.
milliseconds
console.log(timestamp); // Output: e.g., 1693047600000
Em
Example:
127
Time Standards
The time standard is by which the world regulates clocks and time.
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
● 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
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
129
2. Getting Date Information
ng
ni
ar
Le
ve
si
er
m
130
getMonth(): Returns the month (0-11):
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
console.log(currentDate.getHours()); // Output: 15
m
console.log(currentDate.getMinutes()); // Output: 30
131
value based on current time)
console.log(currentDate.getMilliseconds());
ng
ni
3. Setting Date and Time
ar
You can also change different parts of the date using setter methods.
currentDate.setFullYear(2025);
si
console.log(currentDate);
er
currentDate.setMonth(11); // December
currentDate.setDate(25);
132
Setting Hours, Minutes, and Seconds
setHours(): Sets the hour:
currentDate.setHours(14); // 2:00 PM
ng
ni
currentDate.setMinutes(45);
ar
setSeconds(): Sets the seconds:
currentDate.setSeconds(30);
Le
ve
si
4. Formatting Dates
er
133
toDateString(): Returns only the date 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
console.log(currentDate.toLocaleTimeString()); // Output:
"2:45:30 PM" (depending on locale)
Em
134
The timestamp is the number of milliseconds since January 1, 1970 (Unix
Epoch).
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
135
Method Description
ng
getDate() Returns the day of the month (1-31)
ni
getDay() Returns the day of the week (0-6, 0 is
ar
Sunday)
getMinutes()
Le
Returns the minutes (0-59)
ve
setFullYear() Sets the year
()
()
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
introduced a more traditional class-based syntax, but under the hood, JavaScript
remains a prototype-based language.
Em
137
ng
ni
ar
Le
ve
si
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
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
ng
function Person(name, age) {
ni
this.name = name;
ar
this.age = age;
this.greet = function() {
};
Le
console.log("Hello, " + this.name);
}
ve
ES6 Classes:
Em
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
140
greet() {
console.log("Hello, " + this.name);
}
}
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);
}
}
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
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
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
145
ng
ni
ar
Le
Example of Polymorphism:
ve
class Animal {
si
makeSound() {
er
}
Em
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
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
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
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
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
<html>
Em
<body>
<h1>Hello, World!</h1>
<p>This is a paragraph.</p>
</body>
</html>
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
152
ng
ni
ar
Le
ve
The first step in manipulating the DOM is to select the elements you want to
si
153
ng
ni
ar
1. getElementById()
Le
ve
si
er
m
Em
154
○ Selects an element by its ID.
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
4. querySelector()
m
○ Selects the first element that matches a CSS selector (like #id,
Em
.class, tag).
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
2. Changing Styles:
○ You can update the CSS styles of an element using the style
property.
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
element.classList.add('newClass');
element.classList.remove('oldClass');
er
element.classList.toggle('active');
m
Em
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
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.
keydown, etc.
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);
159
ng
ni
ar
Le
ve
parentNode: Get the parent of an element.
si
160
nextElementSibling and previousElementSibling: Navigate to the next
or previous sibling element.
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
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
1. document
2. document.body
163
● Example: document.body.innerHTML gets or sets the HTML inside the
body.
3. document.head
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
7. element.tagName
164
8. element.innerHTML
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
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.
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.
element.
er
17. element.innerHTML
m
166
Common DOM Methods
1. getElementById()
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
● Example: document.querySelector('div').
5. querySelectorAll()
6. createElement()
167
● Creates a new HTML element.
● Example: const newElement =
document.createElement('div').
7. createTextNode()
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
10. replaceChild()
m
oldElement).
11. setAttribute()
12. getAttribute()
168
● Gets the value of an attribute.
● Example: element.getAttribute('href').
13. removeAttribute()
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
● Example: element.removeEventListener('click',
handleClick).
16. cloneNode()
169
● Example: const clone = element.cloneNode(true).
17. insertBefore()
ng
18. scrollIntoView()
ni
● Scrolls the element into view.
ar
● Example: element.scrollIntoView().
19. focus()
20. blur()
si
● Example: inputElement.blur().
m
Em
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
<script>
// Select the button
const button = document.getElementById('changeText');
171
// Select the heading element
const heading = document.getElementById('mainHeading');
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
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
174
ng
ni
ar
Le
ve
si
er
Event Handling
m
Em
175
ng
ni
ar
Le
ve
si
er
m
176
ng
ni
ar
1. Inline Event Handlers
Le
You can add event handlers directly in the HTML by using event attributes like
ve
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
<script>
m
178
</body>
</html>
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
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
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
Example:
ng
function sayHello() {
alert('Hello!');
ni
}
ar
// Add an event listener
button.addEventListener('click', sayHello);
Event Object
m
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
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
<!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
});
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.
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
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.
ng
ni
ar
Le
ve
si
er
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.
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
height=400');
Em
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.
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
console.log(navigator.userAgent);
m
3. screen Object
191
The screen object provides information about the user's display screen, such as
its width, height, and color depth.
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:
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:
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
console.log(location.pathname);
Em
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
history.back();
m
history.forward();
194
6. JavaScript Timers: setTimeout and setInterval
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():
setInterval(function() {
er
195
The BOM allows developers to interact with the browser beyond just the
document content. With BOM, you can:
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
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
Common Methods:
m
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');
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
Common Methods:
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:
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
sessionStorage.clear();
er
m
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
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
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
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
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
2. Reading a Cookie
Em
You can read cookies using document.cookie, which returns all cookies as a
single string.
203
To read a specific cookie, you'll need to parse the string manually.
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
3. Updating a Cookie
m
To update a cookie, you simply overwrite the cookie with the same name:
Em
4. Deleting a Cookie
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
205
document.cookie = "username=JohnDoe; domain=example.com";
4. secure: The cookie will only be sent over secure (HTTPS) connections.
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
Expiry Can be set manually or use Local Storage: persists until deleted, Session
er
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
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
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
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
"Processing data"
m
Em
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
Promise States:
m
Creating a Promise:
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 Keyword:
await Keyword:
213
● The await keyword is used inside an async function to wait for a promise
to be resolved or rejected.
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
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
215
3. File Operations: Reading/writing files in environments like Node.js.
4. Event Handling: Handling user interactions asynchronously.
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.
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
tasks without blocking the main thread. Whether using callbacks, promises, or
the modern async/await syntax, understanding how JavaScript manages
er
code.
Em
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. Using XMLHttpRequest
Em
Basic Example:
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
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
In a POST request, data is sent to the server. You can specify additional options
Em
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
You can also use async/await syntax with fetch to make the code look more
Em
synchronous.
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
Installing 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
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.
ng
● .text(): Converts the response to plain text.
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('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
● 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
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
226
JavaScript more powerful, concise, and easier to work with. Let's dive into some
of the most important ES6+ features:
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.
Differences:
si
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}!`;
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
Benefits:
228
● Expression interpolation for embedding variables
4. Default Parameters
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
Array Destructuring:
m
console.log(a); // 10
console.log(b); // 20
Object Destructuring:
229
console.log(age); // 25
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 }
function sum(...numbers) {
si
ES6 introduced a shorthand syntax for creating objects from variables and
defining methods.
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
});
er
fetchData
.then((result) => console.log(result)) // Output: "Data
m
fetched"
.catch((error) => console.error(error));
Em
Key Points:
231
9. Classes
class Person {
constructor(name, age) {
ng
this.name = name;
this.age = age;
}
ni
greet() {
ar
console.log(`Hello, my name is ${this.name}.`);
}
}
Key Concepts:
si
JavaScript now supports native modules to break your code into separate files.
// file: math.js
232
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
// file: app.js
ng
import { add, subtract } from './math.js';
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
} 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.
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
undefined.
m
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.
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
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.
<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
<script>
function showMessage() {
alert('Hello, this is JavaScript in action!');
}
</script>
</body>
236
</html>
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.
selector.
Em
Example:
<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:
<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.
<script>
er
function validateForm() {
const name = document.getElementById('name').value;
m
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 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
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.
240
// Retrieve data from local storage
const name = localStorage.getItem('name');
console.log(name); // Output: John Doe
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
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.
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.
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
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
ni
conditions. There are several types of testing approaches used in JavaScript
ar
development:
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
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
function add(a, b) {
return a + b;
Em
module.exports = add;
245
expect(add(1, 2)).toBe(3);
});
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
You can also test for error handling, edge cases, or even asynchronous code:
m
// divide.js
function divide(a, b) {
Em
module.exports = divide;
// divide.test.js
246
const divide = require('./divide');
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
247
// Check if the input field is present and type a task
cy.get('.new-todo').type('Buy milk{enter}');
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
TDD ensures that your code is well-tested and designed from the start, reducing
the likelihood of bugs.
248
6. Debugging Tools
● 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
● Write Tests Early: Try to write tests as you develop, rather than after the
code is finished. This helps catch bugs early.
m
● 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
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