0% found this document useful (0 votes)
3 views

JavaScript full note

This document provides a comprehensive overview of JavaScript fundamentals, including syntax, data types, variables, control structures, functions, and methods for manipulating strings and arrays. It covers essential concepts such as type conversion, arithmetic operations, conditional statements, loops, and the use of built-in methods like .forEach(), .map(), and .filter(). Additionally, it introduces advanced topics like the spread operator, rest parameters, and callback functions.

Uploaded by

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

JavaScript full note

This document provides a comprehensive overview of JavaScript fundamentals, including syntax, data types, variables, control structures, functions, and methods for manipulating strings and arrays. It covers essential concepts such as type conversion, arithmetic operations, conditional statements, loops, and the use of built-in methods like .forEach(), .map(), and .filter(). Additionally, it introduces advanced topics like the spread operator, rest parameters, and callback functions.

Uploaded by

henotech HD
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

JavaScript 001

Tip { always link your JavaScript file at the bottom of your html body. }

<!DOCTYPE html>

<html lang="en">

<head>
<link rel="stylesheet" href="style.css" /> <!-- linking css file
-->
<title>js</title>
</head>
<body>
<p id="myp" > < p >
<script src="script.js"></script> <!--linking js file-->
</body>
</html>

color in css
hsla(hue, saturation, lightness, alpha)
The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not transparent at
all):

comments
// single line comment
/ multi line comment */

output
console.log("hello"); //to output on console ( you can also use single quote or
backticks ) { use it like print or cout }
window.alert("how are you"); // this is an alert ( popup window)

adding things to our html elements (output on web)


document.getElementById("myp").textContent = " Hello" ; // here we use our
html elements id and add a text to it.
example: let age =10;
document.getElementById ("myp").textContent=your age is ${age};

VARIABLES
let x; // variable declaration {variable name needs to be unique}
x=10; // variable assignment
let x = 10; // declaration and assignment together.

Note:

you can use ${ } for a formatted string like python but only with backticks.
eg: let age = 10 ;
console.log( you are ${age} years old. ) // output: you are 10 years old.

to display data type use " typeof "


console.log(typeof age); // output: number

Arithmetic operations
we have + , - , * , / , ** , % and increment/decrement
example: ```let product = 3;
product = product 7; // same as product =2;
let remainder = 17 % 5; // Result: 2;

post and pre increment/decrement


let x = 5;
let post = x++; // uses the value and then increments it. here the value is 5.
let y = 5;
let pre=++y; // increments the value then uses it . here the value is 6.

we use "BODMAS"

Accepting input
- we have to ways

1. using window prompt


let name = window.prompt("what is your name?"); //This asks you for your name with
a prompt window on your browser
and stores it in the variable.
console.log(name); //To display your name

2 . Using HTML TEXTBOX


HTML
` username

Login js let username; document.getElementById("sub").onclick=function(){`

username = document.getElementById("txt").value;

`window.alert(Hi , ${username} ); } `

the above code takes a value from the input text box and assigns it to the variable username
and then displays the message in alert mode

Type conversion( typecasting)

Implicit Conversion:

JavaScript automatically converts types in certain situations. For example, when you
use non-numeric strings with minus ( - ), multiplication ( * ), or division ( / ) operators,
JavaScript tries to convert the strings to numbers.
If you try to add a number to a string, the number will be converted into a string and
concatenated.

Explicit Conversion:

You can also convert values manually using certain functions:


Number(value) : Converts the value to a number. If the value cannot be
converted, it returns NaN .
String(value) : Converts the value to a string.
Boolean(value) : Converts the value to a Boolean. Falsy values
like 0 , null , undefined , NaN , "" (empty string) are converted to false , and
all other values are converted to true .

example of explicit type conversion in JavaScript:

let stringValue = "123";


let numberValue = Number(stringValue); // Converts string to number
let booleanValue = Boolean(stringValue); // Converts string to boolean (true)

let numberAsString = String(numberValue); // Converts number back to string


``

const // a variable with a value that can't be changed


example: a program that calculates circumference of a circle.
const pi = 3.14;
let radius , circumference;
radius = window.prompt("radius?");
radius = Number(radius);
circumference = 2 * pi * radius;
window.alert(circumference);

Math in js
Math.PI , Math.E , Math.log(x) , Math.sin(x) , Math.sqrt(x) , Math.pow(x,y);
, Math.abs(x);
Math.round(x); // rounds the number x
Math.floor(x); // always rounds to smallest
Math.ceil(x); // always rounds to largest
Math.trunc(x); // removes the decimal part
Math.sign(x); // to find the sign of x. (+1 , -1 or 0)
Math.min(x,y,z);
Math.max(x,y,z);
Math.random(); // gives you random number b/n 0 and 1

example: Random number generator in the range (x , y)


const x =50;
const y=100;
let random = Math.floor(Math.random()*(y-x))+x;
console.log(random);

IF statement
if (condition 1) {
task to be done
}
else if(condition 2){
task 2
}
else {
task 3
}

.checked
used to determine the checked state of an HTML checkbox or radio button element
example : checked.html in the programs folder

Ternary operator
condition ? value_if_true : value_if_false

example: const x=2;


let y = x > 1 ? "Yes" : "No" ;
console.log(y);

Switch
switch (expression) {
case value1:
// Code block executed if expression matches value1
break;
case value2:
// Code block executed if expression matches value2
break;
// More cases...
default:
// Code block executed if no match is found
}
example:
let score = 80;
let grade;

switch (true) {

case score > 85:


grade = "A";
break;
case score > 70:
grade = "B";
break;

case score > 60:


grade = "C";
break;

default:
grade = "F";
break;
}
console.log(grade);`

string methods
used to manipulate text (string).

1. .charAt(index) returns the character at the specified index.


example:
let text = "HELLO";
let char1 = text.charAt(0); // char1 will be "H"
console.log(char1) // output : H `
2. .indexOf() method in JavaScript. It’s used to find the index of the first occurrence of
a substring within a string.
example:
let str = 'finding substring in string';
let index = str.indexOf('str');
console.log(index); // Output: 11
3. .length property returns the length of a string.
example:
let text = "Hello, World!";
let len = text.length; // len will be 13
4. .trim() method in JavaScript is used to remove leading and trailing whitespace
(spaces, tabs, or line breaks) from a string.
example:
let text = " Hello, World! ";
let trimmedText = text.trim();
console.log(trimmedText); // Output: "Hello, World!"
5. .toUpperCase() and .toLowerCase() // makes everything in the string Upper and
Lower case respectively.
6. .repeat(x) method in JavaScript allows you to create a new string by repeating an
existing string x number of times.
example:
const holiday = "Happy holiday!";
const result = holiday.repeat(2);
console.log(result); `// Happy holiday!Happy holiday!
7. .startsWith(searchString) :
Checks if a string starts with the specified searchString .
Example: JavaScript

let text = "Hello, World!";


let startsWithHello = text.startsWith("Hello");
console.log(startsWithHello); // Output: true

8. .endsWith(searchString) :
Checks if a string ends with the specified searchString .
Example: JavaScript

let text = "Hello, World!";


let endsWithWorld = text.endsWith("World!");
console.log(endsWithWorld); // Output: true

9. .includes(searchString) :
Checks if a string contains the specified searchString .
Example: JavaScript

let text = "Hello, World!";


let containsHello = text.includes("Hello");
console.log(containsHello); // Output: true

10. .replaceAll(searchValue, replaceValue) :


Replaces all occurrences of searchValue with replaceValue in the string.
Example: JavaScript

let text = "Hello, World!";


let replacedText = text.replaceAll("o", "X");
console.log(replacedText); // Output: "HellX, WXXrld!"

11. .padStart(targetLength, padString) :


Pads the string from the start with padString until it reaches the targetLength .
Useful for aligning text.
Example: JavaScript
let number = "42";
let paddedNumber = number.padStart(5, "0");
console.log(paddedNumber); // Output: "00042"

12. .padEnd(targetLength, padString) :


Pads the string from the end with padString until it reaches the targetLength .
Example: JavaScript

let text = "Hello";


let paddedText = text.padEnd(10, "-");
console.log(paddedText); // Output: "Hello-----"

13. .slice(starting index, ending index) creates a new string without modifying the
original one.
example:
let text = "Hello, World!";
let slicedText = text.slice(7, 12);
console.log(slicedText); // Output: "World"

let slicedEnd = text.slice(-6); // Equivalent to text.slice(7)


console.log(slicedEnd); // Output: "World!"

Eg: displaying first name and last name separately


const fullName = "Henok Binayew";
let firstName = fullName.slice(0, fullName.indexOf(" "));
let lastName = fullName.slice(fullName.indexOf(" ") , );
console.log(firstName); //"Henok"
console.log(lastName); // "Binayew"
14. split() :allows you to divide a string into an array of substrings based on a specified
separator. If you want to split on multiple separators (e.g., both commas and spaces), you
can pass in a regular expression as the parameter.
example:
const inputString = "Hello awesome, world!";
const substrings = inputString.split(/[\\s,]+/);
console.log(substrings); // ["Hello", "awesome", "world!"]
14. join() : it joins all elements of an array into a single string, using a specified separator.
For instance:
const words = ["Hello", "awesome", "world!"];
const joinedString = words.join(" ");
console.log(joinedString); // "Hello awesome world!"

method chaining
calling one method after the other in a continuous line of code.
example:
let username = window.prompt("what is your name?");
username= username.trim().charAt(0).toUpperCase() +
username.trim().slice(1,).toLowerCase();
window.alert(your name is ${username} );`

logical operators
! Not
&& and "NAOL" // PRECIDENCE
|| or

operators
= // Assignment operator
== // comparision operator 3 == "3"
!= // inequality operator
=== //strict equality operator(compare if values & datatype are equal)
!== //strict inequality operator 3 !== "3"

While Loop
while(condition){
task
}

do While Loop
do{
task
}while(condition);

for loop
for(let i = 0; i < 3; i++){
console.log(i);
}
continue; //skips an iteration
break; // ends the loop

function
function name(){ //function declaration
task
}
name() //function calling

example:
function add(x,y){
let z = x + y;
return z; //if there is no return the output will be undefined
}
window.alert(add(1,2));

isNaN(x) // true if x is not a number

Local vs Global Variable


Local : inside the function.
:unique in the function.
Global : outside of any function.
:unique everywhere.

Array
let x = [1,2,3]; // array
console.log(x[0]); //1
console.log(x[3]); // undefined
x[1]=4; // modifying

Methods in array
x.push(4); // adds 4 to the end of an array
x.pop(); // removes the last element
x.unshift(0); // adds 0 to the beginning of the array
x.shift(); // removes the 1st object
x.length; // number of elements of an array
x.indexOf(3); // 2 if the element doesn't exist it returns -1
x.sort(); //ascending order
x.reverse(); //descending order
//we can use string methods for an array

spread operator (...)


allows an iterable such as an array or string to be expanded into separate elements.
(unpack the elements)
example:
let x = [1,2,3,4,5];
let maximum=Math.max(x); // NaN
let maximum=Math.max(...x); //5
let minimum=Math.min(...x); //1

let myArray = "henok";


console.log(...myArray); // ["h" ,"e" ,"n" ,"o" ,"k" ]

we can also use them to add to arrays


let x = [1,2];
let y = [3,4];
let z = [...x , ...y,5];
console.log(z); //(4) [1, 2, 3, 4 ,5]

rest parameters (...rest)


bundles separate elements into an array.

example: allows a function to work with a variable number of arguments.


function zoo(...animals){ //The ...animals syntax collects all passed
arguments into an array named animals ,
console.log(animals);
}
const a1="lion";
const a2= "cat";
const a3="dog";
zoo(a1, a2 , a3); // (3) ['lion', 'cat', 'dog']
- rest operator is commonly used in array destructuring to capture remaining elements into a
separate array variable.

const [first, second, ... theRest] = [1, 2, 3, 4, 5];


console.log(first); // First element: 1
console.log(second); // Second element: 2
console.log(theRest); // Rest of the element: [3,4,5]

callback
A function that is passed as an argument to another function.
used for asynchronous operations. like : reading a file and network request.
example:
function x (result) {
console.log(result);
}
function sum(callback , a , b ){
let result = a + b;
callback(result);
}
sum(x , 1 , 2); //displays 3

.forEach()
method used to iterate over the elements of an array and apply a specified function
(callback) to each elements
For each element in the array, the callback function is executed.
The callback function receives three parameters: the current element , its index ,
and the entire array .
Does not create a new array; operates on the original array in place.
array.forEach(callback);

example:
let x = [1, 2, 3, 4, 5];

function displayWithIndexNumber(element, index, array) {


console.log("x(" + index + ") = " + element);
} // this is our call back function and the 3 parameters are provided by
default

x.forEach(displayWithIndexNumber); //we will apply the callback function for


each element in the array.

.map()
accepts a callback and it applies that function to each elements of an array and then
returns a new array.
same as forEach but this creates new array(doesn't modify the original).
example:
const x = [1, 2, 3, 4, 5];
function square(element, index, array) {
return Math.pow(element, 2);
}
let y = x.map(square);
console.log(x); //(5) [1, 2, 3, 4, 5]
console.log(y); //(5) [1, 4, 9, 16, 25]

.filter()
creates a new array by filtering out elements.
example:

const x = [1, 2, 3, 4, 5];


function isOdd(element) {
return element % 2 !== 0;
}
let y = x.filter(isOdd);
console.log(y);

.reduce()
reduces elements of an array to a single element.
example:
const price = [5 ,30 ,10 ,25 ,15 , 20];
const total = price.reduce(sum);
console.log($${total.toFixed(2)}); //$105.00
function sum (accumulator , element){
return accumulator + element;
}
accumulator : The value previously returned by the callback.
With Initial Value:
- The accumulator ( acc ) starts with the provided initial value.
- The iteration includes all elements of the array.
example: const grades = [75, 50, 90, 80, 65, 95];
function getMax(acc, curr) {
return Math.max(acc, curr);
}
// Initializing the accumulator with -Infinity to ensure it works with
any set of numbers
const maximum = grades.reduce(getMax, -Infinity);
console.log(maximum); // Output: 95
Without Initial Value:
- The accumulator ( acc ) starts with the first element.
- The iteration starts from the second element.
currentValue : Each element in the array, one by one.

Example-2 : finding max value from an array.

const grades = [75, 50, 90, 80, 65, 95];

const maximum = grades.reduce(getMax);

function getMax(accumulator, element) {

return Math.max(accumulator, element);

}
Initial Accumulator ( acc ): Not specified, so the first element of the array is used by default
( 75 ).

Step-by-Step Execution

First Iteration:
acc = 75 , curr = 50
Math.max(75, 50) = 75
New acc = 75
Second Iteration:
acc = 75 , curr = 90
Math.max(75, 90) = 90
New acc = 90
Third Iteration:
acc = 90 , curr = 80
Math.max(90, 80) = 90
New acc = 90
Fourth Iteration:
acc = 90 , curr = 65
Math.max(90, 65) = 90
New acc = 90
Fifth Iteration:
acc = 90 , curr = 95
Math.max(90, 95) = 95
New acc = 95
Final acc (maximum value) = 95

Function expression
defining a function as a value or variable.
example: Anonymous Function Expression(You create an unnamed function and
assign it to a variable.)
const hello = function(){
console.log("Hello , World")
};
hello(); // Hello , World

setTimeout( callback , wait Time in mile sec); // 1s = 1000 ms


example:
setTimeout(hello ,3000); // "Hello , World" will be displayed after 3s
or we can just put the whole function as an argument.

setTimeout( function () {
console.log("Hello , World"); } , 3000);

We don't need function name when using function expression

clearTimeout(timeoutid)
cancel a timeout before it triggers.
example:

const timeoutid = setTimeout(()=>window.alert("Hello"),3000);


clearTimeout(timeoutid); //nothing happens after 3s

arrow function: (parameters) => some code


1. Basic Syntax:
Arrow functions use the => syntax.
Example:

JavaScript

const sum = (a, b) => a + b; //it includes "return" by defualt

This is equivalent to the traditional function expression:

JavaScript

const sum = function(a, b) {


return a + b;
};

2. Shorter Syntax:
If the function has only one statement that returns a value, you can omit the curly
braces and the return keyword.
Example: JavaScript

const sayHello = () => "Hello, World!";

3. Parameters:

- If your function takes parameters, enclose them in parentheses.


- Example:

JavaScript
```javascript
const greet = (name) =>console.log( "Hello, " + name);
greet("Henok"); // Hello, Henok
```
here if you do more than 1 task use curly brace:
```javascript
const greet = (name) => {console.log( "Hello, " + name);

console.log("Welcome!"); }
greet("Henok"); // Hello, Henok
// Welcome!

``````
more example:
setTimeout( ( ) =>console.log( "hello") , 2000); // will output "hello" after 2s

one difference between normal function and arrow functions


is:
in an arrow function the this key word is defined in the scope where the function is
defined.
while in the normal function the this keyword is defined in the scope where the function
is called.
example:

here: the last two lines are same.

OBJECT
collection of related properties and/or methods( functions that belong to an object ) that
can represent real world objects.(people ,p products , places ).
object = { key:value or/and function() }
example:
const student1 = {
name: "Henok",
age: 19,
year: 2,
employed: false, //this and the above 3 are properties
greet: function () { console.log("how are you?"); }, // method
};
console.log( student1.name ); //Henok
student1.greet(); // how are you?
delete student1.age // delete age property
console.log( year in student1); // true

this
is a reference to the object where this is used. example:

1. Object Methods:
In an object method, this refers to the object itself. It allows access to the
object’s properties and methods within the method’s scope.
Example: JavaScript

const person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;//same as
person.lastName
}
};

Here, this refers to the person object.


2. Alone (Global Scope):
When used alone (outside any function or object), this refers to the global object
(usually the browser window).
Example: JavaScript

let x = this; // Refers to the global object( Window )

3. Strict Mode:
In strict mode, when used alone, this is undefined .
Example: JavaScript

"use strict";
let x = this; // Now, `this` is `undefined`

#### *we don't use `this` with the `arrow function.`*


# constructor
- is a special method for defining the properties and methods of objects.
example:
`function car (make , year ,color){ //defining
constructor`
`this.make = make,`
`this.year = year,`
`this.color = color`
`}`
`const car1 = new car("ford" , 2024 , "red");//using constructor
with the " new " keyword`
`const car2 = new car("bmw" ,2004 , "blue");`
`console.log(car1.make); //ford`
# Class
**classes** provide a way to create blueprints for objects, Let’s explore
a simple example by creating a `Person` class:

JavaScript

```javascript
// Define a class named 'Person'
class Person {
constructor(name , age) {
this.name = name;
this.age = age;
}

sayHi() {
console.log(`Hello, my name is ${this.name}!`);
}
}

// Create an instance of the Person class


const person1 = new Person("Alice");
person1.sayHi(); // Output: "Hello, my name is Alice!"
console.log(person1.age);

class are like a blue print for the house and the object is the
house. and we use the constructor in side of the class + the
"new" key word are used to change the class (blue print ) into
an object( house ).
example :
//class
class House{
constructor(color){
this.color = color;
}
furniture(){
return "sofa";
}
}
//object
const house1 = new House("red");
const house2 = new House("green");
//output
console.log(house1.color);
console.log(house2.color);
console.log(house1.furniture());

Static
A static method is a function that belongs to the class itself, not to its instances
(objects).
You define a static method using the static keyword within the class.
These methods are often utility functions, like creating or cloning objects.
Example

class User {
static pi = 4;
static staticMethod() {
console.log("This is a static method.");
}
}
console.log(user.pi); //4 * we just use the name of the class
we dont nedd to create an
object to access it. *
User.staticMethod(); // Output: "This is a static method."

Inheritance
allows a new class to inherit properties and methods from an existing class using the
extends keyword.
example:

class animal{
alive = true;
eat() {
console.log(`This ${ this.name} is eating`);
}
}
//child class(extended from parent)
class fish extends animal{
name="fish";
}

class cat extends animal{


name="cat";
}

//objects
const fish1 = new fish();
const cat1 = new cat();

//output
fish1.eat(); //This fish is eating
console.log(cat1.alive); // true

super
allows you to access properties and methods from the parent class (also known as the
superclass).
Note that super() must be called before using this in the constructor of the derived
class.

```javascript
class Rectangle {
constructor(height, width) {
this.name = "Rectangle";
this.height = height;
this.width = width;
}
// Other methods...
}

class Square extends Rectangle {


constructor(length) {
// Call the parent class's constructor with the provided length
super(length, length);
this.name = "Square";
}
}
```
example 2:

JavaScript

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

greet() {
console.log(`Hello, my name is ${this.name}.`);
}
}

class Student extends Person {


constructor(name, studentId) {
// Call the parent class's constructor using super
super(name);
this.studentId = studentId;
}

study() {
console.log(`${this.name} is studying.`);
}
}

const alice = new Student("Alice", 12345);


alice.greet(); // Output: Hello, my name is Alice.
alice.study(); // Output: Alice is studying.

getter/setter
getters and setters are used to define how object properties are accessed and updated.
example:

class Person {
constructor(name, age) {
this._name = name; // Use a private variable (conventionally with
an underscore)
this._age = age;
}

// Setter for name


set name(newName) {
if (typeof newName === 'string') {
this._name = newName;
} else {
console.error('Name must be a string');
}
}
// Getter for name
get name() {
return this._name;
}

// Setter for age


set age(newAge) {
if (typeof newAge === 'number' && newAge > 0) {
this._age = newAge;
}
else {
console.error('Age must be a positive number');
}
}

// Getter for age


get age() {
return this._age;
}

let person = new Person('John', 25);

// Using getters
console.log(person.name); // John
console.log(person.age); // 25

// Using setters
person.name = 'Jane';
person.age = 30;

console.log(person.name); // Jane
console.log(person.age); // 30

// Invalid assignments
person.name = 123; // Name must be a string
person.age = -5; // Age must be a positive number
destructuring
used for extracting values from arrays and objects, then assign them to variables in a
convenient way.
[] = to perform array destructuring
{ } = to perform object destructuring

5 - examples
1)Swap the value of two variables

let a = 1;
let b = 2;
[a,b] = [b,a];
console.log(a); //2
console.log(b); //1

2) to swap 2 elements in an array

const colors = ["red" , "green" , "blue" ,"black" , "white"];


[colors[0],colors[4]] = [colors[4],colors[0]];
console.log(colors); //["white" , "green" , "blue" ,"black" , "red"];

3) to assign array elements to variables

const colors = ["red" , "green" , "blue" ,"black" , "white"];


const[color1 , color2 , ... extraColors]= colors;
console.log(color1); // red
console.log(color2); // green
console.log(extarColors); // ["blue", "blacck" , "white"]

4) to extract values from an object

const person1 = {
name = "henok",
age = 19,
job = "freelancer",
}
const person2 = {
name = "samri",
age = 14,
}
const {Name1 , Age1 , Job1 = "Unemployed"} = person1;
const {Name2 , Age2 , Job2 = "Unemployed"} = person2;
console.log(Name1); //henok
console.log(Age1); //19
console.log(Job1);//freelancer

console.log(Name2); //samri
console.log(Age2); //12
console.log(Job2);//Unemployed

5)Destructure in function parameter

function display({firstName ,age ,job = "Unemployed"}){


console.log(firstName);
console.log(age);
console.log(job);
}
const person1 = {
name = "afomia",
age = 13,

}
display(person1); //afomia
//13
//Unemployed

Nested objects
Objects inside of other objects.
Allows you to represent more complex data structures.
child object is inside of parent object
example: person{ Address{ }, contactInfo{ } }
example2:

const person = {
name:spongebob ,
age: 30 ,
hobbies: ["karate" , "jellyFishing" , "cooking"] , //we can also add an
array
adress: { //nested object
street:"124 conch st." ,
city: "bikini bottom"
}
}
console.log(person.hobbies[0]); //karate
console.log(person.adress.city); //bikini bottom

Arrays of object
example:
const fruits = [{name:"apple" , color : "red"},
{name:"orange" , color : "orange"}
{name:"banana" , color : "yellow"}
{name:"mango" , color : "green"} ]
console.log(fruits[0].name); //apple

.sort()
is used to sort the elements of an array.
By default, it sorts the elements as strings in ascending order.

1. Alphabetical Sorting:
If you have an array of strings (e.g., ["Banana", "Orange", "Apple",
"Mango"] ), calling .sort() will arrange them alphabetically: ["Apple",
"Banana", "Mango", "Orange"] .
Keep in mind that this method overwrites the original array.
2. Numerical Sorting:
When sorting numbers, the default behavior can be problematic. For
example, "25" is considered greater than "100" because "2" comes
after "1" .
To sort numbers correctly, you can provide a custom comparison function. For
ascending order, use:

const points = [40, 100, 1, 5, 25, 10];


points.sort((a, b) => a - b);
// Result: [1, 5, 10, 25, 40, 100]

The (a, b) => a - b function subtracts b from a . If the result is


negative, a comes before b .
For descending order, use:
const points = [40, 100, 1, 5, 25, 10];
points.sort((a, b) => b - a);
// Result: [100, 40, 25, 10, 5, 1]

3. Finding Lowest and Highest Values:


To find the lowest value:

const points = [40, 100, 1, 5, 25, 10];


points.sort((a, b) => a - b);
const lowest = points[0];
// Result: 1

To find the highest value:

```javascript
const points = [40, 100, 1, 5, 25, 10];
points.sort((a, b) => b - a);
const highest = points[0];
// Result: 100
```

more examples:

Date objects
Can be changed or formatted.
Date(year, month, day, hour, minute, second, millisecond)
const date = new Date();

console.log(date); // gives you the current date

//to give a custom date

const date = new Date(2004, 0, 1, 3, 30,20,40);


console.log(date); //Thu Jan 01 2004 03:30:20 GMT+0300 (East Africa Time)

//to get endividual values from date object


const year =date.getFullYear();
const month =date.getMonth();
const day =date.getDate();
const dayofWeek =date.getDay();
const hour =date.getHours();
const minuets =date.getMinutes();
const seconds =date.getSeconds();
console.log(Date.now()); //to get the epic date (from start of time)

// to set the date


date.setFullYear(2024);
date.setMonth(0);
date.setDate(1);
date.setHours(2);
date.setMinutes(3);
date.setSeconds(4);

console.log(date) //Mon Jan 01 2024 02:03:04 GMT+0300 (East Africa Time)

//we can compare dates


const date1 = new Date("2023-12-31");
const date2 = new Date("2024-01-01");
if(date2 > date1){
console.log("HAPPY NEW YEAR!");
}

Closure
created when a function is defined within another function.
The inner function has access to the variables and scopes of the outer function.
Allows for privet variables and state maintenance used frequently in js frameworks like
react ,Vue ,Angular.
example:
function outer(){
let message = "Hello";
function inner(){
console.log(message);
}
return inner();
}

example2: game point counter

function createGame(){
let score = 0;
function increaseScore(points){
score += points;
console. log(`+${points}pts`);
}
function decreaseScore(points){
score-=points;
console. log(`+${points}pts`);
}
function getScore(){
return score;
}
return {increaseScore,decreaseScore, getScore};
}
const game =createGame();
game.increaseScore(5); // +5pts
game.decreaseScore(2);// -2pts
console.log(game.getScore(5));//3

ES6 Module
An external file that contains reusable code that can be imported into other JavaScript
files.
We can Write reusable code for many different applications. and can contain variables,
classes, functions and more.
Introduced as part of ECMAScript 2015 update
example:
HTML-File:
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
<style></style>
</head>
<body>
<script src="index.js" type="module"></script>
</body>
</html>
Module-File: ( mathUtill.js )

export const pi = 3.14159;

export function area(radius){


return 2*pi*radius**2
}

Js-File (index.js)

import {pi,area} from `./mathUtill.js`;

console.log(pi); //3.14159

console.log(Math.floor(area(2)); // 25

synchronous
Executes line by line consecutively in a sequential manner Code that waits for an
operation to complete.
Each operation waits for the previous one to complete before executing.
example:

console.log('One');
console.log('Two');
console.log('Three');
// LOGS: 'One', 'Two', 'Three'

asynchronous
Allows multiple operations to be performed concurrently without waiting Doesn't block
the execution flow and allows the program to continue (1/0 operations, network
requests, fetching data) Handled with: callbacks, promises, A sync/Await
Error
An Object that is created to represent a problem that occurs.
Occur often with user input or establishing a connection.
Errors can be generated from different issues like : NETWORK ERRORS, PROMISE
REJECTION, SECURITY ERRORS

types of errors
1. Syntax Error: This error occurs when the code contains invalid syntax. For example,
missing a closing bracket or using a reserved keyword incorrectly.
2. Reference Error: This happens when a non-existent variable is referenced. For
example, trying to use a variable that hasn’t been declared.
3. Type Error: This error is thrown when a value is not of the expected type. For example,
calling a non-function as if it were a function.
4. Range Error: This occurs when a value is not within the set or expected range. For
example, creating an array with an invalid length.

Handling Errors
1. try { }
Encloses code that might potentially cause an error
2. catch { }
Catch and handle any thrown Errors from try { }
3. finally { } ¯
(optional) Always executes.
used mostly for clean up.
ex. close files, close connections, release resources
example:

try{
console.log(x);
}
catch(error){
console.error(error);
}
finally {
// CLOSE FILES
// CLOSE CONNECTIONS
// RELEASE RESOURCES
console.log("This always executes");
}
console.log("You have reached the end")
/* output : ReferenceError: x is not defined
at practice.html:10:21
This always executes
You have reached the end
*/

4. throw : keyword is used to create a custom error. When you use throw , it stops the
execution of the current function and passes control to the nearest catch block in the
call stack. If no catch block is found, the program will terminate.

function checkNumber(num) {
if (typeof num !== 'number') {
throw new Error('Not a number!');
}
return num;
}

try {
checkNumber('abc');
} catch (e) {
console.error(e.message); // Outputs: Not a number!
}

In this example, if checkNumber is called with a non-number argument, it throws an error,


which is then caught and handled in the catch block.

DOM
The DOM (Document Object Model) is a structured representation of an HTML
document that the web browser creates when it loads a page. It’s like a tree of objects
where each element on the page (like a heading, paragraph, or button) is a node in this
tree.
JavaScript can interact with the DOM, allowing you to dynamically change the content,
structure, and style of a web page. This means you can add or remove elements,
modify text, change styles, and more—all without needing to reload the page.

Example:

Hello, World!
Click Me
In this example, clicking the button changes the text of the heading from "Hello, World!" to
"Hello, DOM!" using JavaScript to interact with the DOM.

Key Points:
DOM Structure: Elements are arranged in a tree-like structure.
Access: JavaScript can access and manipulate the DOM.
Dynamic Changes: You can modify content, structure, and styles dynamically.

This interaction between JavaScript and the DOM is what makes web pages dynamic and
interactive.

Essential DOM methods


1. document.getElementById()
What it does: Selects an element by its unique ID.
Example:
let element = document.getElementById('myDiv');
element.style.color = 'blue';

2. document.getElementsByClassName()
What it does: Selects all elements with a given class name.
Example:
let elements = document.getElementsByClassName('myClass');
elements[0].style.fontSize = '20px';

3. document.getElementsByTagName()
What it does: Selects all elements with a given tag name (like div , p , etc.).
Example:
let paragraphs = document.getElementsByTagName('p');
paragraphs[0].textContent = 'Updated paragraph text';

4. document.querySelector()
What it does: Selects the first element that matches a CSS selector.
Example:
let element = document.querySelector('.myClass'); // use . when using class
name
// let element = document.querySelector('h4'); //we can also use a tag name
element.style.backgroundColor = 'yellow';

5. document.querySelectorAll()
What it does: Selects ( by id, class or element) all elements that match a CSS selector.
and returns a Node list ( we use indexing to access each one )
A NodeList is a static collection of HTML elements obtained
using querySelectorAll() . It’s similar to an array, but it lacks methods
like map , filter , or reduce . Additionally, a NodeList won’t automatically update to
reflect changes in the DOM.
Example:
let elements = document.querySelectorAll('div');
elements.forEach(el => el.style.border = '1px solid black');

THESE ARE ELEMENT SELECTORS

6. element.textContent
What it does: Gets or sets the text content of an element.
Example:
let heading = document.getElementById('heading');
heading.textContent = 'New Heading Text';

7. element.innerHTML
What it does: Gets or sets the HTML content of an element.
Example:
let div = document.getElementById('myDiv'); div.innerHTML = '
New paragraph inside the div
';`

8. element.style
What it does: Directly modifies the inline styles of an element.
Example:
let button = document.querySelector('button');
button.style.backgroundColor = 'green';
9. element.setAttribute()
What it does: Sets the value of an attribute on an element.
Example:
let img = document.querySelector('img');
img.setAttribute('alt', 'A descriptive text');

10. element.getAttribute()
What it does: Gets the value of an attribute from an element.
Example:
let link = document.querySelector('a');
let hrefValue = link.getAttribute('href');

11. element.classList.add()
What it does: Adds a class to an element.
Example:
let div = document.getElementById('myDiv');
div.classList.add('newClass');

12. element.classList.remove()
What it does: Removes a class from an element.
Example:
let div = document.getElementById('myDiv');
div.classList.remove('oldClass');

13. element.classList.toggle()
What it does: Toggles a class on or off.
Example:
let div = document.querySelector('div');
div.classList.toggle('highlight');

14. element.addEventListener()
What it does: Attaches an event listener to an element.
Example:
let button = document.querySelector('button');
button.addEventListener('click', function() { alert('Button clicked!');
});

15. element.remove()
What it does: Removes an element from the DOM.
Example:
let div = document.getElementById('myDiv');
div.remove();

16. document.createElement()
What it does: Creates a new element.
Example:
let newDiv = document.createElement('div');
newDiv.textContent = 'I am a new div!';
document.body.appendChild(newDiv);

17. element.appendChild()
What it does: Adds a new child element to a parent element.
Example:
let parent = document.getElementById('parentDiv');
let child = document.createElement('p');
child.textContent = 'New Child Element';
parent.appendChild(child);

18. element.insertBefore()
What it does: Inserts a new element before another specified element.
Example:
let parent = document.getElementById('parentDiv'); let newElement =
document.createElement('p'); newElement.textContent = 'Inserted Before!';
parent.insertBefore(newElement, parent.firstChild);

19. element.removeChild()
What it does: Removes a child element from a parent element.
Example:
let parent = document.getElementById('parentDiv');
let child = document.getElementById('childDiv');
parent.removeChild(child);

20. element.replaceChild()
What it does: Replaces a child element with a new element.
Example:
let parent = document.getElementById('parentDiv');
let newChild = document.createElement('p');
newChild.textContent = 'Replaced Child';
parent.replaceChild(newChild, parent.firstChild);

DOM navigation
1. firstElementChild :
Explanation: Returns the first child element of a specified element.
Example: If you have an element with an ID of “myDiv,” you can get its first child
element like this:

const parent = document.getElementById("myDiv");


const firstChild = parent.firstElementChild;

2. lastElementChild :
Explanation: Returns the last child element of a specified element.
Example: To get the last child element of a parent element with the class “myList,”
you can do:

const lastChild =
document.querySelector(".myList").lastElementChild;

3. nextElementSibling :
Explanation: Returns the next sibling element at the same tree level.
Example: If you have an element with the class “current,” you can get its next
sibling element like this:

const
nextSibling=document.querySelector(".current").nextElementSibling
;

4. previousElementSibling :
Explanation: Returns the previous sibling element at the same tree level.
Example: To find the previous sibling of an element with the ID “myLink,” you can
use:
javascript
constprevSibling=document.getElementById("myLink").previousElementSi
bling;
5. parentElement :
Explanation: Returns the parent element of a specified element.
Example: If you want to access the parent element of an element with the class
“childItem,” use:

const parent =
document.querySelector(".childItem").parentElement;

6. children :
Explanation: Returns a collection of child elements (excluding text and comment
nodes) of a specified element.
Example: To get all child elements of an element with the ID “myContainer,” you
can do:

const childElements =
document.getElementById("myContainer").children;

Changing HTML elements in JS


1. Creating an Element:
- To create an HTML element dynamically, use document.createElement(tagName) .
For example:
```javascript
const newH1 = document.createElement("h1");
newH1.id = "myH1";
newH1.classList = "myclass"; // Adding a class
//or
newH1.classList.add("myStyle");
newH1.classList.remove("myStyle"); //to remove the class
newH1.classList.toggle("myStyle"); //adds the class if it’s not present and removes it if it
is
newH1.classList.replace("oldClass", "newClass");
const hasMyStyle = newH1.classList.contains("myStyle"); //to check if an element has a
specific class.Returns true or false.

newH1.textContent = "I like pizza";


newH1.style.color = "tomato";
newHI.style.textAIign "center" ;
myElement.style.top = '';
myElement.style.left = '';

```

2. **Appending the Element to the DOM:**


2. Adding an Element
- To add the newly created element to the document, you can use
methods like `appendChild()`,`prepend()` or `.insertBefore(element,
reference)`.
For instance:
```javascript
document.getElementById("container").appendChild(newH1); //adds newH1 at
the last line in the container
// Or use: document.body.appendChild(newH1); to add to the body

document.getElementById("container").prependChild(newH1); //adds newH1 at


the first line in the container

const box2 document.getE1ementById("box2");


document.body.insertBefore(newH1, box2); // adds newH1 before box2
```

3. **Removing an Element:**
- If you want to remove an element, use `removeChild()`:

```javascript
document.getElementById("box").removeChild(newH1);
```
# Event Listeners

Event listeners allow you to respond to specific events (such as clicks,


mouse movements, or keyboard input) on HTML elements. They make your web
pages interactive by executing code when an event occurs. Here’s how you
can use them:
1. **Basic Syntax:**

- The `addEventListener()` method attaches an event handler to an


element.
- It takes three parameters:
- The type of the event (e.g., `"click"`, `"mouseover"`).
- The function to call when the event occurs.
- An optional boolean value (`true` for event
capturing, `false` for event bubbling).
2. **Example: Adding a Click Event Listener:**
```javascript
const button = document.querySelector("#myButton");
button.addEventListener("click", () => {
console.log("Button clicked!");
});
```

In this example, when the button with the ID `"myButton"` is clicked,


the message `"Button clicked!"` will be logged to the console

1. **Adding Multiple Event Handlers:** You can add multiple event handlers
to the same element without overwriting existing ones:
```javascript
const myElement = document.querySelector("#myElement");
myElement.addEventListener("click", myFunction);
myElement.addEventListener("mouseover", mySecondFunction);
// ... add more event handlers
```
4. **Using Named Functions:** You can also refer to an external named
function:

```javascript
function myFunction() {
console.log("Hello from myFunction!");
}
myElement.addEventListener("click", myFunction);
```

5. **Event Listeners on Window Object:** You can add event listeners to


any DOM object, including the window object:
```javascript
window.addEventListener("resize", () => {
console.log("Window resized!");
});
```

6. **Passing Parameters:** When passing parameter values, use an anonymous


function that calls the specified function with the parameters:
```javascript
const myButton = document.querySelector("#myButton");
myButton.addEventListener("click", () => {
myCustomFunction("Hello, world!");
});

function myCustomFunction(message) {
console.log(message);
}
```
### Example Using an Image

Let’s create an example using an image. Suppose you have an image element
with the ID `"myImage"` and you want to change its source when clicked:

1. **HTML:**

```html
<img id="myImage" src="initial-image.jpg" alt="My Image">
<button id="changeImage">Change Image</button>
```

```javascript
const imageElement = document.querySelector("#myImage");
const buttonElement = document.querySelector("#changeImage");

buttonElement.addEventListener("click", () => {
imageElement.src = "new-image.jpg";
});
```
## Common Events
# 1. **Mouse Events**:

A. **`click`**: Detects when a button is pressed and released on a


single element. For example:

```javascript
document.getElementById("myButton").addEventListener("click",
function() {
console.log("Button clicked!");
});
```

B. **`dblclick`**: Occurs when an element is clicked twice in quick


succession. Example:

```javascript
document.getElementById("myElement").addEventListener("dblclick",
function() {
console.log("Double-clicked!");
});
```

C. **`mouseover`**: Fired when the mouse pointer moves over an element.


Example:

```javascript
document.getElementById("myDiv").addEventListener("mouseover",
function() {
console.log("Mouse over the div!");
});
```
D. **`mouseout`**: Triggers when the mouse leaves an element. Example:

```javascript
document.getElementById("myLink").addEventListener("mouseout",
function() {
console.log("Mouse left the link!");
});
```

E. **`mousemove`**: Occurs when the mouse is moving while over an element.


Example:

```javascript
document.addEventListener("mousemove", function(event) {
console.log(`Mouse position: X=${event.clientX},
Y=${event.clientY}`);
});
```
# 2. **Keyboard Events**:
==Note: - `event.key`: Returns the character that has been pressed (e.g.,
‘z’ for the ‘z’ key).==
==- `event.code`: Returns the physical key code (e.g., ‘KeyZ’ for the
‘z’ key).==

A. **`keydown`**: Fired when a key is pressed down. Example:

```javascript
document.addEventListener("keydown", function(event) {
console.log(`Key pressed: ${event.key}`);
});
```

B. **`keyup`**: Triggered when a key is released. Example:

```javascript
document.addEventListener("keyup", function(event) {
console.log(`Key released: ${event.key}`);
});
```
==// USE KEYDOWN INSTEAD OF KEYPRESS==
C. **Keypress Event**:
- The `keypress` event occurs when the user presses a key that produces a
character value. These include keys such as alphabetic, numeric, and
punctuation keys.
- Modifier keys like ‘Shift’, ‘CapsLock’, and ‘Ctrl’ do not produce a
character value, so they do not trigger a keypress event].
example:
```javascript
document.addEventListener("keypress", () =>
console.log(event.key));
```

# 3. **Submit Event**:

- Triggered when a user submits a form (e.g., by clicking a submit


button).
- Example: Handling form submission:

```javascript
const myForm = document.getElementById("myForm");
myForm.addEventListener("submit", function(event) {
event.preventDefault(); // Prevent actual form submission
// Process form data here
});
```

# 4. **Load Event**:
- Fires when an element (e.g., an image or entire page) finishes loading.
- Example: Execute code after the page has loaded:

```javascript
window.addEventListener("load", function() {
console.log("Page loaded!");
});
```

# **Callback hell**
refers to the situation in JavaScript where multiple nested callbacks
create complex, deeply indented code, often called the “pyramid of doom.”
This structure makes the code difficult to read, debug, and maintain,
resulting in poor code quality and scalability issues.

### Example of Callback Hell

```javascript
function firstTask(callback) {
setTimeout(() => {
console.log('First Task');
callback();
}, 1000);
}

function secondTask(callback) {
setTimeout(() => {
console.log('Second Task');
callback();
}, 1000);
}

function thirdTask(callback) {
setTimeout(() => {
console.log('Third Task');
callback();
}, 1000);
}

// Executing tasks in order


firstTask(() => {
secondTask(() => {
thirdTask(() => {
console.log('All tasks completed');
});
});
});

In this example:

Each task is executed after the previous one completes, leading to deeply nested
callbacks.
This structure can quickly become unmanageable as more tasks are added.
To avoid callback hell, you can use Promises or async/await syntax, which makes
the code more readable and easier to maintain.

Promises in JavaScript
A Promise is an object representing the eventual completion or failure of an asynchronous
operation. It allows you to write asynchronous code in a more synchronous fashion, making
it easier to handle asynchronous operations.

States of a Promise:

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


2. resolved: The operation completed successfully.
3. Rejected: The operation failed.

Example with resolve , reject , then() , and catch()

Here’s an example demonstrating how to create and use a Promise:

// Creating a new Promise


let myPromise = new Promise((resolve, reject) => { /* A promise is
created using the `Promise` constructor, which takes a function with two
parameters: `resolve` and `reject`. */
let success = true; // Change this to false to see the reject case

if (success) {
resolve("Operation was successful!");
} else {
reject("Operation failed!");
}
});

// Consuming the Promise


myPromise
.then((message) => {
console.log(message); // This will run if the promise is resolved
})
.catch((error) => {
console.error(error); // This will run if the promise is rejected
});

In this example:

The resolve function is called if the operation is successful.


The reject function is called if the operation fails.
The then() method handles the resolved case.
The catch() method handles the rejected case.

Promise Chaining
When you want to perform a series of asynchronous tasks one after another, you can
chain .then() calls.
You can handle errors in a promise chain using .catch() . If any promise in the chain is
rejected, the control jumps to the nearest .catch() .

new Promise((resolve, reject) => {


setTimeout(() => resolve(1), 1000);
})
.then((result) => {
console.log(result); // 1
return result * 2;
})
.then((result) => {
console.log(result); // 2
return result * 2;
})
.then((result) => {
console.log(result); // 4
});

more example

const a = new Promise((resolve, reject) => setTimeout(() => resolve("A"),


4000));
const b = new Promise((resolve, reject) => setTimeout(() => resolve("B"),
2500));
const c = new Promise((resolve, reject) => setTimeout(() => resolve("C"),
1000));
a.then((message) => {
console.log(message);
return b;
}).then((message) => {
console.log(message);
return c;
}).then((message) => console.log(message));

Promise.all()
Is a static method that takes an iterable (such as an array) of promises as input and
returns a single promise. This returned promise resolves when all of the input
promises have resolved, or it rejects if any of the input promises reject.
When you use Promise.all() , it returns a single promise that resolves to an array
containing the resolved values of all the input promises, in the same order as they were
passed in.

const a = new Promise((resolve, reject) => setTimeout(() => resolve("A"),


4000));
const b = new Promise((resolve, reject) => setTimeout(() => resolve("B"),
2500));
const c = new Promise((resolve, reject) => setTimeout(() => resolve("C"),
1000));

Promise.all([a, b, c]).then((messages) => {


console.log(messages[0]); // Logs "A"
console.log(messages[1]); // Logs "B"
console.log(messages[2]); // Logs "C"
console.log(messages); // ["A","B","C"]
});
Async and Await in JavaScript
Async/Await is a modern syntax to work with Promises, making asynchronous code look
and behave more like synchronous code. It is built on top of Promises and provides a
cleaner and more readable way to handle asynchronous operations.

Example with async and await

// Function that returns a Promise


function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data fetched successfully!");
}, 2000);
});
}

// Async function using await


async function getData() {
try {
const result = await fetchData(); // Waits for the promise to resolve
console.log(result); // Logs "Data fetched successfully!"
} catch (error) {
console.error(error); // Handles any errors
}
}

getData();

In this example:

The async keyword is used to declare an asynchronous function.


The await keyword is used to wait for the Promise to resolve or reject.
The try...catch block is used to handle any errors that might occur during the
asynchronous operation.

General Example
//creating a Promise

const task1 = new Promise((resolve, reject) => resolve("wake up"));


const task2 = new Promise((resolve, reject) => resolve("Pray"));
const task3 = new Promise((resolve, reject) => setTimeout(() =>
resolve("go to gym"), 3000));
const task4 = new Promise((resolve, reject) => setTimeout(() =>
resolve("eat and sleep"), 5000));

//using Promise Chaining

task1
.then((message) => {
console.log(message);
return task2;
})
.then((message) => {
console.log(message);
return task3;
})
.then((message) => {
console.log(message);
return task4;
})
.then((message) => {
console.log(message);
});

//using Promise.all
Promise.all([task1,
task2,task3,task4]).then((messages)=>console.log(messages));

// Using Async/ Await

async function getData() {


const T1 = await task1;
console.log(T1);
const T2 = await task2;
console.log(T2);
const T3 = await task3;
console.log(T3);
const T4 = await task4;
console.log(T4);
}
getData();

Json ( JavaScript Object Notation )


It is a data-interchange format used for exchanging data between a server and a web
application.
Json files can be in a { key : value } //object OR [value1,value2,value3]
//array
JSON.stringify()

Converts a JavaScript object to a JSON string.

const obj = { name: "Alice", age: 25 };


const jsonString = JSON.stringify(obj);
console.log(jsonString); // Output: '{"name":"Alice","age":25}'

JSON.parse()

Converts a JSON string to a JavaScript object.

const jsonString = '{"name":"Alice","age":25}';


const obj = JSON.parse(jsonString);
console.log(obj.name); // Output: Alice

fetch()
Used for making HTTP requests to fetch resources such as JSON data, images, or
files. It simplifies asynchronous data fetching and is commonly used for interacting with
APIs.
It initiates a network request and returns a promise that resolves to
the Response object representing the response to that request.

Example:

// GET request
fetch('https://api.example.com/data')
.then(response => response.json()) // Parses JSON response into a JS
object
.then(data => console.log(data)) // Use the data
.catch(error => console.error('Error:', error));

// POST request
const data = { name: "Alice", age: 25 };

fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data) // Convert JS object to JSON string
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));

Explanation:

GET request:
fetch('https://api.example.com/data') initiates a GET request to the
specified URL.
.then(response => response.json()) parses the JSON response into a
JavaScript object.
.then(data => console.log(data)) handles the parsed data.
.catch(error => console.error('Error:', error)) catches and logs any
errors.
POST request:
fetch('https://api.example.com/data', { method: 'POST', headers: {
'Content-Type': 'application/json' }, body: JSON.stringify(data)
}) initiates a POST request with the specified options.
The body contains the JSON stringified data to be sent.
The rest of the .then and .catch methods handle the response and errors
similarly to the GET request.

.json()
A method of the Response object that parses the JSON response into a JavaScript object.

Example:

fetch('https://api.example.com/data')
.then(response => response.json()) // Parses JSON response
.then(data => console.log(data)) // Use the data
.catch(error => console.error('Error:', error));

Explanation:

response.json() is called on the Response object returned by fetch .


It returns a promise that resolves with the result of parsing the response body text as
JSON.
This parsed data can then be used in your application.

You might also like