0% found this document useful (0 votes)
51 views90 pages

CO1 Notes

The document provides a comprehensive overview of JavaScript basics, covering topics such as syntax, variables, data types, operators, control flows, arrays, and functions. It explains how to execute statements, define variables using 'let', 'const', and 'var', and utilize various operators and control structures like loops and conditionals. Additionally, it introduces array methods and the use of the rest and spread operators, along with examples to illustrate each concept.

Uploaded by

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

CO1 Notes

The document provides a comprehensive overview of JavaScript basics, covering topics such as syntax, variables, data types, operators, control flows, arrays, and functions. It explains how to execute statements, define variables using 'let', 'const', and 'var', and utilize various operators and control structures like loops and conditionals. Additionally, it introduces array methods and the use of the rest and spread operators, along with examples to illustrate each concept.

Uploaded by

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

Javascript Basics

// This is hard to read


console.log("Hello World!"); console.log("I'm learning JavaScript");

// Now it's better


console.log("Hello World!");
console.log("I'm learning JavaScript");
Comments
// This is a comment
// This is also a comment

// Below print two lines of statements


console.log("Hello World!");
console.log("I'm learning JavaScript");
Execution Flow
A language processor such as Node.js executes statements in a top-down approach. The
statement written in the first line will be executed before the second line, then continue down to
the last line:

console.log("Hello World!");
console.log("I'm learning JavaScript");

// Printing numbers
console.log(1);
console.log(2);
console.log(3);
Output:
Hello World!
I'm learning JavaScript
1
2
3
JavaScript Variables
let message = "Hello World!"
console.log(message)
message = "Hello World!"
print(message)
message = "Nice weather!"
print(message)
Run the file and you'll see two lines printed as the output:

Hello World!
Nice weather!

JavaScript has two naming conventions that are used worldwide:

1. camelCase
let myAwesomeVariable

2. snake_case
let my_awesome_variable

Constant variable
const FILE_SIZE_LIMIT = 2000
const MAX_SPEED = 300

The var keyword


The var keyword is used to declare variables with a global scope.
if(true) {
var name = "Nathan";
}

console.log(name)
JavaScript Basic Data Types
● Strings
● Numbers
● Booleans
● Null
● Undefined
let name = "John";
let topic = "JavaScript";

console.log(name + " is learning " + topic + " today");


console.log(`${name} is learning ${topic} today`);

Numbers (integers and floats) in JavaScript


● Integers
● Floats
Booleans in JavaScript
Boolean is a type that represents true and false values.

let on = true;
let off = false;
Undefined in JavaScript
Undefined is a data type in JavaScript used to represent a variable that hasn't been assigned any
value yet.

Null in JavaScript
The null value is a special data type that represents an empty or unknown value. Here's how you
assign a variable as null:
let first_name = null;
Type Conversion and Coercion
let x = "7";
let y = 5;

console.log(x + y); // 75
● Number()
● String()
● Boolean()

let x = "7";
let y = 5;

// Convert x to integer
x = Number(x);

console.log(x + y); // 12
Operators in JavaScript
Arithmetic operators

Operation
Name example Meaning
Addition x+y Returns the sum between the two operands
Subtraction x-y Returns the difference between the two operands
Multiplication x*y Returns the multiplication between the two operands
Returns the value of the left operand raised to the
Exponentiation x ** y power of the right operand
Returns the value of the left operand divided by the
Division x/y right operand
Returns the remainder of the left operand after being
Remainder x%y divided by the right operand
Increment x++ Returns the operand plus one
Decrement x-- Returns the operand minus one

assignment operators:

Operation
Name example Meaning
Assignment x=y x=y
Addition assignment x += y x=x+y
Subtraction assignment x -= y x=x-y
Multiplication assignment x *= y x=x*y
Division assignment x /= y x=x/y
Remainder assignment x %= y x=x%y
Next, let's look at comparison operators.

The comparison operators


Operation
Name example Meaning
Equal x == y Returns true if the operands are equal
Not equal x != y Returns true if the operands are not equal
Returns true if the operands are equal and have the
Strict equal x === y same type
Returns true if the operands are not equal, or have
Strict not equal x !== y different types
Returns true if the left operand is greater than the
Greater than x>y right operand
Greater than or Returns true if the left operand is greater than or
equal x >= y equal to the right operand
Returns true if the left operand is less than the right
Less than x<y operand
Less than or Returns true if the left operand is less than or equal to
equal x <= y the right operand

Logical operators
Operation
Name example Meaning
Logical AND x && y Returns true if all operands are true, else returns false
Returns true if one of the
Logical operands is true, else
OR `x y` returns false
Reverse the result:
Logical returns true if false and vice
NOT !x versa
The typeof operator
let x = 5;
console.log(typeof x) // 'number'

console.log(typeof "Nathan") // 'string'

console.log(typeof true) // 'boolean'

Control Flows (Conditionals) in JavaScript


1. if...else statement
2. switch...case statement

if (condition) {
// code to execute if condition is true
}

let balance = 7000;

if (balance > 5000) {


console.log("You have the money for this trip. Let's go!");
} else {
console.log("Sorry, not enough money. Save more!");
}
console.log("The end!");

let balance = 7000;

if (balance > 5000) {


console.log("You have the money for this trip. Let's go!");
} else if (balance > 3000) {
console.log("You only have enough money for a staycation");
} else {
console.log("Sorry, not enough money. Save more!");
}
console.log("The end!");

The switch...case statement


The switch statement is a part of core JavaScript syntax that allows you to control the execution
flow of your code.
let age = 15;
switch (age) {
case 10:
console.log("Age is 10");
break;
case 20:
console.log("Age is 20");
break;
default:
console.log("Age is neither 10 or 20");
}

let age = 5;

switch (age) {
case age < 10:
console.log("Value is less than ten");
break;
case age < 20:
console.log("Value is less than twenty");
break;
default:
console.log("Value is twenty or more");
}

Control Flows (Loops) in JavaScript


● The for statement
● The while statement
for (let x = 0; x < 10; x++) {
console.log(x);
}
The while statement
while (condition) {
statement;
}

JavaScript Arrays
let birds = ['Owl', 'Eagle', 'Parrot', 'Falcon'];
You can think of an array as a list of items, each stored in a locker compartment:

You can also declare an empty array without any value:


let birds = [];
An array can also have a mix of values like this:

let mixedArray = ['Bird', true, 10, 5.17]


// Access the first element in the array
myArray[0];

let birds = ['Owl', 'Eagle', 'Parrot', 'Falcon'];

console.log(birds[0]); // Owl
console.log(birds[1]); // Eagle

let birds = ['Owl', 'Eagle', 'Parrot', 'Falcon'];


birds[2] = 'Vulture';

console.log(birds);
// ['Owl', 'Eagle', 'Vulture', 'Falcon']
let birds = ['Owl', 'Eagle'];

birds.push('Sparrow');

console.log(birds);
// ['Owl', 'Eagle', 'Sparrow']

let birds = ['Owl', 'Eagle', 'Sparrow'];

birds.pop();

console.log(birds);
// ['Owl', 'Eagle']

The unshift() method can be used to add an item from the front at index 0:
let fishes = ['Salmon', 'Goldfish', 'Tuna'];

fishes.unshift('Sardine');

console.log(fishes);
// ['Sardine', 'Salmon', 'Goldfish', 'Tuna']

On the other hand, the shift() method can be used to remove an item from index 0:
let fishes = ['Salmon', 'Goldfish', 'Tuna'];

fishes.shift();

console.log(fishes);
// ['Goldfish', 'Tuna']

The indexOf() method can be used to find and return the index of an item in the array.
The method will return -1 when the item isn't found inside the array:
let fishes = ['Salmon', 'Goldfish', 'Tuna'];

let pos = fishes.indexOf('Tuna');

console.log(pos); // 2

console.log(fishes.length); // 3

—---------
//remove at specific index
let arr = [5, 10, 15, 20, 25];

let index = 2; // index to remove (here, element 15)

// Check if index is valid


if (index >= 0 && index < arr.length) {
arr.splice(index, 1);
}

console.log(arr); // Output: [5, 10, 20, 25]

ar.splice(index, 0, 18);

console.log(arr); // Output: [5,10,18, 20]

// Removes 2 elements starting from index 2 (30 and 40)


let arr = [10, 20, 30, 40, 50];
arr.splice(2, 2);
console.log(arr); // [10, 20, 50]

// At index 2, delete 0 elements, insert 3 and 4


let arr = [1, 2, 5, 6];
arr.splice(2, 0, 3, 4);
console.log(arr); // [1, 2, 3, 4, 5, 6]

Array Iteration:

For loop
let fishes = ['Salmon', 'Goldfish', 'Tuna'];

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


console.log(fishes[i]);
}

while loop
let fishes = ['Salmon', 'Goldfish', 'Tuna'];
let i = 0;

while (i < fishes.length) {


console.log(fishes[i]);
i++;
}

Do while loop:
let fishes = ['Salmon', 'Goldfish', 'Tuna'];
let i = 0;

do {
console.log(fishes[i]);
i++;
} while (i < fishes.length);

For of loop
let fishes = ['Salmon', 'Goldfish', 'Tuna'];

for (let fish of fishes) {


console.log(fish);
}

For Each loop


let fishes = ['Salmon', 'Goldfish', 'Tuna'];
fishes.forEach(function(fish, index) {
console.log(index, fish);
});
This will output each fruit along with its index.

For Each loop with arrow function


let fishes = ['Salmon', 'Goldfish', 'Tuna'];
fishes.forEach((fish, index)=> {
console.log(index, fish);
});

Array Methods:

map()

Purpose

● Transforms each element of an array.

● Returns a new array of the same length.

Syntax
array.map((element, index, array) => {
// return new value
});

Example
const numbers = [1, 2, 3, 4];

const squared = numbers.map(num => num * num);

console.log(squared); // [1, 4, 9, 16]


filter()

Purpose

● Filters out elements based on a condition.

● Returns a new array with only elements that pass the condition.

Syntax
array.filter((element, index, array) => {
// return true to keep the element, false to exclude
});

Example
const numbers = [1, 2, 3, 4, 5, 6];

const evens = numbers.filter(num => num % 2 === 0);

console.log(evens); // [2, 4, 6]

reduce()

Purpose

● Reduces an array to a single value (e.g. sum, product, concatenation).

● Applies a function with an accumulator on each element.

Syntax
array.reduce((accumulator, currentValue, index, array) => {
// return updated accumulator
}, initialValue);
Example: Sum of numbers
const numbers = [1, 2, 3, 4];

const sum = numbers.reduce((acc, num) => acc + num, 0);

console.log(sum); // 10

Example: Find maximum


const numbers = [10, 50, 30, 70, 20];

const max = numbers.reduce((acc, num) => (num > acc ? num : acc), numbers[0]);

console.log(max); // 70

Example: Square only even numbers and find their sum (using all)
const numbers = [1, 2, 3, 4, 5, 6];

const result = numbers


.filter(num => num % 2 === 0) // [2,4,6]
.map(num => num * num) // [4,16,36]
.reduce((acc, num) => acc + num, 0); // 4+16+36 = 56

console.log(result); // 56

Key Differences

Function Returns Use case

map() New array (same length) Transform each element

filter() New array (<= original) Select elements based on condition

reduce() Single value Aggregate or combine to single output


● map:.
const upperCaseFruits = fruits.map(fruit => fruit.toUpperCase());
console.log(upperCaseFruits); // ['APPLE', 'BLUEBERRY', 'ORANGE', 'MANGO']
● filter:
const longFruits = fruits.filter(fruit => fruit.length > 5);
console.log(longFruits); // ['Blueberry', 'Orange']
● reduce:
const totalLength = fruits.reduce((acc, fruit) => acc + fruit.length, 0);
console.log(totalLength); // 22 (sum of lengths of all fruits)

Rest Operator (...) Example

● Rest Operator (...): Collects remaining elements into an array or object.

with arrays

Imagine you are building a simple checkout system where you want to sum up the prices of
products, but the number of products may vary:

function calculateTotalPrice(basePrice, ...additionalPrices) {


const totalPrice = additionalPrices.reduce((acc, price) => acc + price, basePrice);
return totalPrice;
}

const total = calculateTotalPrice(100, 20, 15, 30, 10);


console.log(`Total Price: $${total}`); // Output: Total Price: $175

With Objects

Sometimes you might only want to exclude a specific property and keep the rest:

const product = {
name: 'Laptop',
brand: 'Dell',
price: 1000,
stock: 50
};
// Excluding 'price' and collecting the rest into 'productDetails'
const { price, ...productDetails } = product;

console.log(price); // Output: 1000


console.log(productDetails); // Output: { name: 'Laptop', brand: 'Dell', stock: 50 }

Spread Operator (...)

● Copies elements from an array or properties from an object into a new array or object.

with arrays
const fruits = ['Apple', 'Blueberry', 'Orange', 'Mango'];

const moreFruits = [...fruits, 'Pineapple', 'Peach'];

console.log(moreFruits);
// Output: ['Apple', 'Blueberry', 'Orange', 'Mango', 'Pineapple', 'Peach']

In this example:
The ...fruits spreads the elements of the fruits array into a new array moreFruits.

New elements ('Pineapple', 'Peach') are added to the array.

with objects
const person = {
name: 'John Doe',
age: 30,
city: 'New York'
};

const updatedPerson = { ...person, city: 'Los Angeles' };

console.log(updatedPerson);
// Output: { name: 'John Doe', age: 30, city: 'Los Angeles' }

Functions in JavaScript
function greet() {
// function body here
console.log("Hello!");
}

greet(); // Hello!

function greet(name) {
console.log(`Hello, ${name}!`);
console.log("Nice weather today, right?");
}
greet("S");

function greet(name = "Nathan") {


console.log(`Hello, ${name}!`);
console.log("Nice weather today, right?");
}
greet();
greet(undefined);
greet( "rosy");

function greet(name = "Nathan", weather) {


console.log(`Hello, ${name}!`);
console.log(`It's ${weather} today, right?`);
}

greet("sunny");
greet(undefined, "sunny");

function greet(name = "John"){


console.log(name);
}

greet(undefined) //replaces default value


greet(null) //null is a value - so null will be printed
function sum(a, b) {
return a + b;
}

let result = sum(3, 2);


console.log(result); // 5

The rest parameter


//array with variable number of arguments
function printArguments(...args){
console.log(args);
}
printArguments("A", "B", "C");
// [ 'A', 'B', 'C' ]
printArguments(1, 2, 3, 4, 5);
// [ 1, 2, 3, 4, 5 ]

Anonymous Function in JavaScript

An anonymous function is a function without a name.

Syntax
function () {
// code block
}

let greet = function() {


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

greet();
//with parameter
let add = function(a, b) {
return a + b;
};

console.log(add(3, 4)); // Output: 7

Arrow function
The JavaScript arrow function syntax allows you to write a JavaScript function with a shorter,
more concise syntax.

//without parameter
let greet = () => {
console.log("Hello!");
};

greet(); // Output: Hello!

//with parameter
const greetings = (name) => {
console.log(`Hello, ${name}!`);
};

greetings("John"); // Hello, John!

const fun = (param1, param2, ...) => {


// function body
}

Using the arrow function, you can omit both the curly brackets and the return keyword, creating
a single line function as shown below:
const plusTwo = (num) => num + 2;
const greetings = () => console.log("Hello World!");

When using the arrow function syntax, the curly brackets are required only when you have a
multiline function body:

const greetings = () => {


console.log("Hello World!");
console.log("How are you?");
};
Arrow function without round brackets
//with one argument alone
const plusThree = num => num + 3;
console.log(plusThree(3))

//no parameter
const greetings = () => console.log("Hello World!");

//more than one parameter


const greetings = (name, age) => console.log("Hello World!");

const printArgs = () => console.log(arguments);

printArgs(1, 2, 3);
//Uncaught ReferenceError: arguments is not defined

const printArgs = (...arguments) => console.log(arguments);

printArgs(1, 2, 3);
// [1, 2, 3]
Objects in JavaScript
An object is a special data type that allows you to store more than one value, just like an array.

The difference between an object and an array is that an array stores data as a list of items, while
an object stores data in a key:value pair format.
let myBook = {
title: "JavaScript Introduction",
author: "Nathan Sebhastian",
};

let myBook = {
title: "JavaScript Introduction",
author: "Nathan Sebhastian",
describe: function () {
console.log(`Book title: ${this.title}`);
console.log(`Book author: ${this.author}`);
},
};
Here, the describe key or property is a function that prints the title and author value from the
object.
The this keyword refers to the context of the code, which is the myBook object in this case.

let myBook = {
title: "JavaScript Introduction",
author: "Nathan Sebhastian",
};

console.log(myBook.title);
console.log(myBook.author);
console.log(myBook["title"]);
console.log(myBook["author"]);

for (let key in myBook) {


if (myBook.hasOwnProperty(key)) { // Ensures the property belongs to the object itself
console.log(`${key}: ${ myBook[key]}`);
}
}

// add release year property


myBook.year = 2023;

// add publisher property


myBook["publisher"] = "CodeWithNathan";

console.log(myBook);

result:

{
title: 'JavaScript Introduction',
author: 'Nathan Sebhastian',
year: 2023,
publisher: 'CodeWithNathan'
}

// change the author property


myBook.author = "John Doe";

console.log(myBook);
Output:

{
title: 'JavaScript Introduction',
author: 'John Doe'
}

delete myBook.author;

console.log(myBook);
Output:
{ title: 'JavaScript Introduction' }

// check if firstName exists


console.log('firstName' in person); // true

// check if age exists


console.log('age' in person); // false

Exercise: Build a Cash Register Machine


Let's build a cash register machine that can add items to a shopping cart, calculate total price,
calculate discounts, and accept payment by cash.

The currency is assumed in USD, so you don't need to add it to the program.

The cash register has 3 items for sale:

● Phone for 300


● Smart TV for 220
● Gaming Console for 150
There's a 10% discount when the total price is higher than 400.

The cash register should have a shopping cart that starts empty.

The cash register should provide a method called addItem that takes the name of an item as a
parameter. When called, it should check if the item is available for sale. If it is, the item should
be added to the shopping cart. If it is not available, show a message saying we don't sell that
item.
The cash register should provide a method called calculateTotalPrice that calculates the total
price of all the items in the shopping cart. It should iterate over the items in the shopping cart and
sum up their prices.
The cash register should provide a method called pay that takes the payment amount as a
parameter.
It should calculate the total price of the items in the shopping cart using
the calculateTotalPrice method. If the total price is higher than 400, a 10% discount should be
applied.
The method should then compare the payment amount with the total price (after applying the
discount) and display an appropriate message:

● If the payment amount is equal to or greater than the total price, it should display a
message thanking the customer for the purchase. If there is any change, it should also
display the amount of change to be given.
● If the payment amount is less than the total price, it should display a message indicating
that the customer does not have enough money to purchase the items.
● The program should include appropriate console.log() statements to display messages for
adding items to the shopping cart, displaying the total price, and processing the payment.
The program should handle scenarios where the customer's payment amount is exactly equal to
the total price, as well as cases where the payment amount is greater or less than the total price.

const cashRegister = {
itemsForSale: [
{ name: "Phone", price: 300 },
{ name: "Smart TV", price: 220 },
{ name: "Gaming Console", price: 150 },
],
shoppingCart: [],
addItem: function (name) {
let foundItem = this.itemsForSale.find(function (item) {
return item.name === name;
});
if (foundItem) {
this.shoppingCart.push(foundItem);
console.log(`Adding ${name} to your shopping cart`);
} else {
console.log(`Sorry, we don't sell ${name} here!`);
}
},
calculateTotalPrice: function () {
let totalPriceAmount = 0;
this.shoppingCart.forEach(function (purchasedItem) {
totalPriceAmount += purchasedItem.price;
});
return totalPriceAmount;
},
pay: function (amount) {
let totalPriceAmount = this.calculateTotalPrice();
if (totalPriceAmount > 500) {
totalPriceAmount -= totalPriceAmount * 0.1;
console.log(
`You get a 10% discount and your total price is ${totalPriceAmount}`
);
}
if (amount >= totalPriceAmount) {
if (amount - totalPriceAmount > 0) {
console.log(`Here's your ${amount - totalPriceAmount} change`);
}
console.log(`Thanks for your purchase! Hope you come again`);
} else {
console.log(
"Sorry, but you don't have enough money to purchase your items"
);
}
},
};
To test the object, run the code below:

cashRegister.addItem("Phone");
cashRegister.addItem("Smart TV");
console.log(cashRegister.calculateTotalPrice());
cashRegister.pay(700);
Output:

Adding Phone to your shopping cart


Adding Smart TV to your shopping cart
520
You get a 10% discount and your total price is 468
Here's your 232 change
Thanks for your purchase! Hope you come again

—--------------------------

HTML DOM (Document Object Model)

When a web page is loaded, the browser creates a Document Object Model of the page.

The HTML DOM model is constructed as a tree of Objects:

The HTML DOM Tree of Objects


HTML DOM

The HTML DOM is a standard object model and programming interface for HTML. It
defines:

● The HTML elements as objects


● The properties of all HTML elements
● The methods to access all HTML elements
● The events for all HTML elements

In other words: The HTML DOM is a standard for how to get, change, add, or delete
HTML elements.

DOM Programming Interface

The HTML DOM can be accessed with JavaScript (and with other programming languages).

In the DOM, all HTML elements are defined as objects.

The programming interface is the properties and methods of each object.

A property is a value that you can get or set (like changing the content of an HTML element).

A method is an action you can do (like add or deleting an HTML element).

Example
The following example changes the content (the innerHTML) of the <p> element
with id="demo":

<html>
<body>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>

</body>
</html>
Finding HTML Elements

Method Description

document.getElementById(id) Find an element by element id

document.getElementsByTagName(name) Find elements by tag name

document.getElementsByClassName(name) Find elements by class name

Changing HTML Elements

Property Description

element.innerHTML = new html content Change the inner HTML of an element


element.attribute = new value Change the attribute value of an HTML element

element.style.property = new style Change the style of an HTML element

Method Description

element.setAttribute(attribute, value) Change the attribute value of an HTML element

Adding and Deleting Elements

Method Description

document.createElement(element) Create an HTML element

document.removeChild(element) Remove an HTML element

document.appendChild(element) Add an HTML element

document.replaceChild(new, old) Replace an HTML element

document.write(text) Write into the HTML output stream


Adding Events Handlers

Method Description

document.getElementById(id).onclick = Adding event handler code to an onclick event


function(){code}

Finding HTML Element by Id

The easiest way to find an HTML element in the DOM, is by using the element id.

This example finds the element with id="intro":

const element = document.getElementById("intro");

Finding HTML Elements by Tag Name

This example finds all <p> elements:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML DOM</h2>

<p>Finding HTML Elements by Tag Name.</p>


<p>This example demonstrates the <b>getElementsByTagName</b> method.</p>

<p id="demo"></p>
<script>
const element = document.getElementsByTagName("p");

document.getElementById("demo").innerHTML = 'The text in first paragraph (index 0) is: ' +


element[0].innerHTML;

</script>

</body>
</html>

const x = document.getElementById("main");
const y = x.getElementsByTagName("p");
Finding HTML Elements by Class Name

If you want to find all HTML elements with the same class name,
use getElementsByClassName().

This example returns a list of all elements with class="intro".

const x = document.getElementsByClassName("intro");

Finding HTML Elements by CSS Selectors

If you want to find all HTML elements that match a specified CSS selector (id, class names,
types, attributes, values of attributes, etc), use the querySelectorAll() method.

This example returns a list of all <p> elements with class="intro".

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML DOM</h2>

<p>Finding HTML Elements by Query Selector</p>


<p class="intro">Hello World!.</p>
<p class="intro">This example demonstrates the <b>querySelectorAll</b> method.</p>

<p id="demo"></p>

<script>
const x = document.querySelectorAll("p.intro");
document.getElementById("demo").innerHTML =
'The first paragraph (index 0) with class="intro" is: ' + x[0].innerHTML;
</script>

</body>
</html>

—-----------------------
Using Query Selector to change the first occurrence of the text to red
<p class="mypara">Paragraph 1</p>
<p class="mypara">Paragraph 2</p>

<script>
// Selects only the first element with class 'mypara'
const firstPara = document.querySelector('.mypara');
firstPara.style.color = 'red';
</script>

—-----------------

Using querySelectorAll

querySelectorAll selects all matching elements as a NodeList, so you can loop through them.

<p class="mypara">Paragraph 1</p>


<p class="mypara">Paragraph 2</p>

<script>
// Selects all elements with class 'mypara'
const allParas = document.querySelectorAll('.mypara');
allParas.forEach(function(para) {
para.style.color = 'red';
});
</script>
—--------------------------
Finding HTML Elements by HTML Object Collections

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML DOM</h2>


<p>Finding HTML Elements Using <b>document.forms</b>.</p>
<form id="frm1">
First name: <input type="text" name="fname" value="Donald"><br>
Last name: <input type="text" name="lname" value="Duck"><br><br>
<input type="submit" value="Submit">
</form>

<p>These are the values of each element in the form:</p>

<p id="demo"></p>

<script>
const x = document.forms["frm1"];
let text = "";
for (let i = 0; i < x.length ;i++) {
text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

—-----------------------------

<!DOCTYPE html>
<html>
<body>

<img id="myImage" src="smiley.gif">

<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>

</body>
</html>

<!DOCTYPE html>
<html>
<body>

<script>
document.getElementById("demo").innerHTML = "Date : " + Date(); </script>

</body>
</html>

FORMS
To validate numbers in the range of 1 to 10

<p>Please input a number between 1 and 10:</p>

<input id="numb">

<button type="button" onclick="myFunction()">Submit</button>

<p id="demo"></p>
<script>
function myFunction() {
// Get the value of the input field with id="numb"
let x = document.getElementById("numb").value;
// If x is Not a Number or less than one or greater than 10
let text;
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html>

Changing HTML Style

<html>
<body>

<p id="p2">Hello World!</p>

<script>
document.getElementById("p2").style.color = "blue";
</script>

</body>
</html>
//chnaging the text color to Red
<!DOCTYPE html>
<html>
<body>

<h1 id="id1">My Heading 1</h1>

<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>

</body>
</html>
JavaScript HTML DOM Events

Examples of HTML events:

● When a user clicks the mouse


● When a web page has loaded
● When an image has been loaded
● When the mouse moves over an element
● When an input field is changed
● When an HTML form is submitted
● When a user strokes a key

The content of the <h1> element is changed when a user clicks on it: (embedded onclick)

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onclick Attribute</h2> // “this” refers to the <h2> element
<h2 onclick="this.innerHTML='Ooops!'">Click on this text!</h2>

</body>
</html>

The content of the <h1> element is changed when a user clicks on it: (through function)

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onclick Attribute</h2>
<h2 onclick="changeText(this)">Click on this text!</h2>
<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>

</body>
</html>

Display Date

<!DOCTYPE html>

<html>

<body>

<h1>JavaScript HTML Events</h1>

<h2>The onclick Attribute</h2>


<p>Click the button to display the date.</p>

<button onclick="displayDate()">The time is?</button>

<script>

function displayDate() {

document.getElementById("demo").innerHTML = Date();

displayDate()

setInterval(displayDate,1000);

</script>

<p id="demo"></p>

</body>

</html>

//calling onclick through script

<!DOCTYPE html>

<html>

<body>

<h1>JavaScript HTML Events</h1>

<h2>The onclick Events</h2>

<p>Click "Try it" to execute the displayDate() function.</p>


<button id="myBtn">Try it</button>

<p id="demo"></p>

<script>

document.getElementById("myBtn").onclick = displayDate;

function displayDate() {

document.getElementById("demo").innerHTML = Date();

</script>

</body>

</html>

//Onload event

<!DOCTYPE html>

<html>

<body onload="checkCookies()">

<h1>JavaScript HTML Events</h1>

<h2>The onload Attribute</h2>

<p id="demo"></p>
<script>

function checkCookies() {

let text = "";

if (navigator.cookieEnabled == true) {

text = "Cookies are enabled.";

} else {

text = "Cookies are not enabled.";

document.getElementById("demo").innerHTML = text;

</script>

</body>

</html>

//Oninput -> changing the case while typing

<!DOCTYPE html>

<html>

<body>

<h1>JavaScript HTML Events</h1>

<h2>The oninput Attribute</h2>

Enter your name: <input type="text" id="fname" oninput="upperCase()">

<script>
function upperCase() {

const x = document.getElementById("fname");

x.value = x.value.toUpperCase();

</script>

</body>

</html>

//Onchange -> changing the case after the focus is lost

<!DOCTYPE html>

<html>

<body>

<h1>JavaScript HTML Events</h1>

<h2>The onchange Attribute</h2>

Enter your name: <input type="text" id="fname" onchange="upperCase()">

<p>When you leave the input field, a function transforms the input to upper case.</p>

<script>

function upperCase() {

const x = document.getElementById("fname");

x.value = x.value.toUpperCase();

</script>
</body>

</html>

//Onmouseover

<!DOCTYPE html>

<html>

<body>

<h1>JavaScript HTML Events</h1>

<h2>The onmouseover Attribute</h2>

<div onmouseover="mOver(this)" onmouseout="mOut(this)"

style="background-color:#D94A38;width:120px;height:20px;padding:40px;">

Mouse Over Me</div>

<script>

function mOver(obj) {

obj.innerHTML = "Thank You"

function mOut(obj) {

obj.innerHTML = "Mouse Over Me"

</script>

</body>

</html>
//onmousedown and up

<!DOCTYPE html>

<html>

<body>

<h1>JavaScript HTML Events</h1>

<h2>The onmousedown Attribute</h2>

<div onmousedown="mDown(this)" onmouseup="mUp(this)">

Click Me</div>

<script>

function mDown(obj) {

obj.style.backgroundColor = "red";

obj.innerHTML = "Release Me";

function mUp(obj) {

obj.style.backgroundColor="green";

obj.innerHTML="Thank You";

</script>

</body>

</html>
JavaScript HTML DOM EventListener

The addEventListener() method attaches an event handler to the specified element.

The addEventListener() method attaches an event handler to an element without overwriting


existing event handlers.

can add many event handlers to one element.

can add many event handlers of the same type to one element, i.e two "click" events.

can add event listeners to any DOM object not only HTML elements. i.e the window object.

The addEventListener() method makes it easier to control how the event reacts to bubbling.

When using the addEventListener() method, the JavaScript is separated from the HTML markup,
for better readability and allows you to add event listeners even when you do not control the
HTML markup.

You can easily remove an event listener by using the removeEventListener() method.

The addEventListener() method

element.addEventListener(event, function, useCapture);

The first parameter is the type of the event (like "click" or "mousedown" or any other DOM
Event.)

The second parameter is the function we want to call when the event occurs.

The third parameter is a boolean value specifying whether to use event bubbling or event
capturing. This parameter is optional.

document.getElementById("myBtn").addEventListener("click", displayDate);

<!DOCTYPE html>
<html>

<body>

<h2>JavaScript addEventListener()</h2>

<button id="myBtn" >Try it</button>

<p id="demo"></p>

<script>

document.getElementById("myBtn").addEventListener("click", displayDate);

function displayDate() {

document.getElementById("demo").innerHTML = Date();

</script>

</body>

</html>

—--------------

Add an Event Handler to an Element


<!DOCTYPE html>

<html>

<body>

<h2>JavaScript addEventListener()</h2>

<button id="myBtn">Try it</button>

<script>
document.getElementById("myBtn").addEventListener("click", function() {

alert("Hello World!");

});

</script>

</body>

</html>

—--------

Add Many Event Handlers to the Same Element


<!DOCTYPE html>

<html>

<body>

<h2>JavaScript addEventListener()</h2>

<button id="myBtn">Try it</button>

<script>

var x = document.getElementById("myBtn");

x.addEventListener("click", myFunction);

x.addEventListener("click", someOtherFunction);

function myFunction() {

alert ("Hello World!");

}
function someOtherFunction() {

alert ("This function was also executed!");

</script>

</body>

</html>

—--------

Add an Event Handler to the window Object

The addEventListener() method allows you to add event listeners on any HTML DOM object
such as HTML elements, the HTML document, the window object, or other objects that support
events, like the xmlHttpRequest object.

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript addEventListener()</h2>

<p id="demo"></p>

<script>

window.addEventListener("resize", function(){

document.getElementById("demo").innerHTML = Math.random();
});

</script>

</body>

</html>

Passing Parameters

When passing parameter values, use an "anonymous function" that calls the specified function
with the parameters:

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript addEventListener()</h2>

<p>Click the button to perform a calculation.</p>

<button id="myBtn">Try it</button>

<p id="demo"></p>

<script>

let p1 = 5;

let p2 = 7;

document.getElementById("myBtn").addEventListener("click", function() {

myFunction(p1, p2);

});
function myFunction(a, b) {

document.getElementById("demo").innerHTML = a * b;

</script>

</body>

</html>

Event Bubbling or Event Capturing

There are two ways of event propagation in the HTML DOM, bubbling and capturing.

Event propagation is a way of defining the element order when an event occurs. If you have a
<p> element inside a <div> element, and the user clicks on the <p> element, which element's
"click" event should be handled first?

In bubbling the inner most element's event is handled first and then the outer: the <p> element's
click event is handled first, then the <div> element's click event.

In capturing the outer most element's event is handled first and then the inner: the <div>
element's click event will be handled first, then the <p> element's click event.

With the addEventListener() method you can specify the propagation type by using the
"useCapture" parameter:

addEventListener(event, function, useCapture);

The default value is false, which will use the bubbling propagation, when the value is set to true,
the event uses the capturing propagation.

<!DOCTYPE html>

<html>

<head>

<style>
#myDiv1, #myDiv2 {

background-color: coral;

padding: 50px;

#myP1, #myP2 {

background-color: white;

font-size: 20px;

border: 1px solid;

padding: 20px;

</style>

<meta content="text/html; charset=utf-8" http-equiv="Content-Type">

</head>

<body>

<h2>JavaScript addEventListener()</h2>

<div id="myDiv1">

<h2>Bubbling:</h2>

<p id="myP1">Click me!</p>

</div><br>

<div id="myDiv2">

<h2>Capturing:</h2>
<p id="myP2">Click me!</p>

</div>

<script>

document.getElementById("myP1").addEventListener("click", function() {

alert("You clicked the white element!");

}, false);

document.getElementById("myDiv1").addEventListener("click", function() {

alert("You clicked the orange element!");

}, false);

document.getElementById("myP2").addEventListener("click", function() {

alert("You clicked the white element!");

}, true);

document.getElementById("myDiv2").addEventListener("click", function() {

alert("You clicked the orange element!");

}, true);

</script>

</body>

</html>

The removeEventListener() method


The removeEventListener() method removes event handlers that have been attached with the
addEventListener() method:

<!DOCTYPE html>

<html>

<head>

<style>

#myDIV {

background-color: coral;

border: 1px solid;

padding: 50px;

color: white;

font-size: 20px;

</style>

</head>

<body>

<h2>JavaScript removeEventListener()</h2>

<div id="myDIV">

<p>Click the button to remove the div's event handler.</p>


<button onclick="removeHandler()" id="myBtn">Remove</button>

</div>

<p id="demo"></p>

<script>

document.getElementById("myDIV").addEventListener("mousemove", myFunction);

function myFunction() {

document.getElementById("demo").innerHTML = Math.random();

function removeHandler() {

document.getElementById("myDIV").removeEventListener("mousemove", myFunction);

</script>

</body>

</html>

DOM Nodes
According to the W3C HTML DOM standard, everything in an HTML document is a node:
● The entire document is a document node
● Every HTML element is an element node
● The text inside HTML elements are text nodes
● Every HTML attribute is an attribute node (deprecated)
● All comments are comment nodes
Node Relationships
The nodes in the node tree have a hierarchical relationship to each other.
The terms parent, child, and sibling are used to describe the relationships.
● In a node tree, the top node is called the root (or root node)
● Every node has exactly one parent, except the root (which has no parent)
● A node can have any number of children
● Siblings (brothers or sisters) are nodes with the same parent
Navigating Between Nodes
You can use the following node properties to navigate between nodes with JavaScript:
● parentNode
● childNodes[nodenumber]
● firstChild
● lastChild
● nextSibling
● previousSibling

Child Nodes and Node Values


A common error in DOM processing is to expect an element node to contain text.
Example:
<title id="demo">DOM Tutorial</title>
The element node <title> (in the example above) does not contain text.
It contains a text node with the value "DOM Tutorial".
The value of the text node can be accessed by the node's innerHTML property:
myTitle = document.getElementById("demo").innerHTML;
Accessing the innerHTML property is the same as accessing the nodeValue of the first child:
myTitle = document.getElementById("demo").firstChild.nodeValue;
Accessing the first child can also be done like this:
myTitle = document.getElementById("demo").childNodes[0].nodeValue;
All the (3) following examples retrieves the text of an <h1> element and copies it into
a <p> element:
Example
<html>
<body>

<h1 id="id01">My First Page</h1>


<p id="id02"></p>

<script>
document.getElementById("id02").innerHTML =
document.getElementById("id01").innerHTML;
</script>

</body>
</html>

Example
<html>
<body>

<h1 id="id01">My First Page</h1>


<p id="id02"></p>

<script>
document.getElementById("id02").innerHTML =
document.getElementById("id01").firstChild.nodeValue;
</script>

</body>
</html>
Example
<html>
<body>

<h1 id="id01">My First Page</h1>


<p id="id02">Hello!</p>

<script>
document.getElementById("id02").innerHTML =
document.getElementById("id01").childNodes[0].nodeValue;
</script>

</body>
</html>
InnerHTML
In this tutorial we use the innerHTML property to retrieve the content of an HTML element.
However, learning the other methods above is useful for understanding the tree structure and the
navigation of the DOM.

DOM Root Nodes


There are two special properties that allow access to the full document:
● document.body - The body of the document
● document.documentElement - The full document
Example
<html>
<body>

<h2>JavaScript HTMLDOM</h2>
<p>Displaying document.body</p>
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = document.body.innerHTML;
</script>

</body>
</html>

Example
<html>
<body>

<h2>JavaScript HTMLDOM</h2>
<p>Displaying document.documentElement</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = document.documentElement.innerHTML;
</script>

</body>
</html>
The nodeName Property
The nodeName property specifies the name of a node.
● nodeName is read-only
● nodeName of an element node is the same as the tag name
● nodeName of an attribute node is the attribute name
● nodeName of a text node is always #text
● nodeName of the document node is always #document
Example
<h1 id="id01">My First Page</h1>
<p id="id02"></p>

<script>
document.getElementById("id02").innerHTML =
document.getElementById("id01").nodeName;
</script>
The nodeValue Property
The nodeValue property specifies the value of a node.
● nodeValue for element nodes is null
● nodeValue for text nodes is the text itself
● nodeValue for attribute nodes is the attribute value

The nodeType Property


The nodeType property is read only. It returns the type of a node.
Example
<h1 id="id01">My First Page</h1>
<p id="id02"></p>

<script>
document.getElementById("id02").innerHTML = document.getElementById("id01").nodeType;
</script>
Example
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
const para = document.createElement("p");
const node = document.createTextNode("This is new.");
para.appendChild(node);

const element = document.getElementById("div1");


element.appendChild(para);
</script>
Creating new HTML Elements - insertBefore()
The appendChild() method in the previous example, appended the new element as the last child
of the parent.
If you don't want that you can use the insertBefore() method:
Example
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
const para = document.createElement("p");
const node = document.createTextNode("This is new.");
para.appendChild(node);

const element = document.getElementById("div1");


const child = document.getElementById("p1");
element.insertBefore(para, child);
</script>

—---------------

Function Sequence
JavaScript functions are executed in the sequence they are called. Not in the sequence they are
defined.

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Functions</h1>
<h2>Function Sequence</h2>
<p>JavaScript functions are executed in the sequence they are called.</p>

<p id="demo"></p>

<script>
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}

function myFirst() {
myDisplayer("Hello");
}

function mySecond() {
myDisplayer("Goodbye");
}

myFirst();
mySecond();
</script>

</body>
</html>

—------------------

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<h2>Function Sequence</h2>
<p>JavaScript functions are executed in the sequence they are called.</p>

<p>The result of the calculation is:</p>


<p id="demo"></p>

<script>
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}

function myCalculator(num1, num2) {


let sum = num1 + num2;
myDisplayer(sum);
}

myCalculator(5, 5);
</script>

</body>
</html>

—-------------

Callback in JavaScript

A callback is:

● A function passed as an argument to another function.

● It is “called back” inside the outer function to complete some action or logic.

In simple words:

✅ You give another function as an input


✅ The main function runs it when ready
<!DOCTYPE html>

<html>

<body>

<h1>JavaScript Functions</h1>

<h2>Callback Functions</h2>

<p>The result of the calculation is:</p>

<p id="demo"></p>

<script>

function myDisplayer(something) {

document.getElementById("demo").innerHTML = something;

function myCalculator(num1, num2, myCallback) {

let sum = num1 + num2;

myCallback(sum);

myCalculator(5, 5, myDisplayer);

</script>

</body>

</html>

Visual summary for your example:


myCalculator ➔ calculates sum ➔ calls myDisplayer ➔ displays result

Why use callbacks?

● To run code after an operation finishes (especially asynchronous operations like API
calls, reading files, database queries, time out, server responses).
● To make functions more flexible and reusable, as they can perform different tasks based
on the callback given. (to make your code more modular and reusable)
● You don’t know what function to run until runtime

—----------------

Sync.js

const posts = [
{title:"One", body:"this is post one"},
{title:"Two", body:"this is post two"}
];
function getPosts(){
setTimeout(()=>{
let output='';
posts.forEach((post,index)=>{
output+=`<li> ${post.title} </li>`;
})
document.body.innerHTML=output;
},1000);
}

function createPost(post){
setTimeout(()=>{
posts.push(post);

},2000);
};

getPosts();

createPost({title:'three', body:'this is post three'});


//getPosts();
Output:
One
Two

//if getposts given after createpost


Output:
One
Two
Three

—-------------------
Callback.js
const posts = [
{title:"One", body:"this is post one"},
{title:"Two", body:"this is post two"}
];
function getPosts(){
setTimeout(()=>{
let output='';
posts.forEach((post,index)=>{
output+=`<li> ${post.title} </li>`;
})
document.body.innerHTML=output;
},1000);
}

function createPost(post, callback){


setTimeout(()=>{
posts.push(post);
callback();
},2000);
};

getPosts();

createPost({title:'three', body:'this is post three'},getPosts);


Output:
One
Two
Three
—------------

JavaScript Promises
JavaScript Promise Object
A Promise contains both the producing code and calls to the consuming code:
Promise Syntax
let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)

myResolve(); // when successful


myReject(); // when error
});

// "Consuming Code" (Must wait for a fulfilled Promise)


myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
When the producing code obtains the result, it should call one of the two callbacks:

When Call

Success myResolve(result value)

Error myReject(error object)

Promise Object Properties


A JavaScript Promise object can be:
● Pending
● Fulfilled
● Rejected
The Promise object supports two properties: state and result.
While a Promise object is "pending" (working), the result is undefined.
When a Promise object is "fulfilled", the result is a value.
When a Promise object is "rejected", the result is an error object.

myPromise.state myPromise.result

"pending" undefined

"fulfilled" a result value

"rejected" an error object

You cannot access the Promise properties state and result.


You must use a Promise method to handle promises.

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


const success = true;
if (success) {
resolve("Task completed successfully!");
} else {
reject("Task failed.");
}
});

myPromise
.then(result => console.log(result)) // runs if resolved
.catch(error => console.log(error)); // runs if rejected
Promise.then() takes two arguments, a callback for success and another for failure.
Both are optional, so you can add a callback for success or failure only.

Promise.js
const posts = [
{title:"One", body:"this is post one"},
{title:"Two", body:"this is post two"}
];
function getPosts(){
setTimeout(()=>{
let output='';
posts.forEach((post,index)=>{
output+=`<li> ${post.title} </li>`;
})
document.body.innerHTML=output;
},1000);
}
function createPost(post){
return new Promise((resolve, reject)=>{
setTimeout(()=>{
posts.push(post);
const error=false; // check with true also -> note the error in console
if(!error)
resolve();
else
reject('Error: Something went wrong');

},2000);
});

//getPosts();

createPost({title:'three', body:'this is post three'})


.then(getPosts)
.catch(err=>console.log(err));

—----------

Promiseall

Promise.all() is a method that takes an array of promises and returns a single promise
that:

● Resolves when all the promises resolve, returning an array of their results.

● Rejects immediately if any promise is rejected, returning the rejection reason.


Syntax
Promise.all([promise1, promise2, promise3])
.then(results => {
// all promises resolved
})
.catch(error => {
// any promise rejected
});

Example

const promise1= Promise.resolve("hello");


const promise2= 10;
const promise3= new Promise((resolve,reject)=>
setTimeout(resolve,2000,"Bye")
);

Promise.all([promise1,promise2,promise3]).then(values=>console.log(values));

Promise.race

Promise.race() is a method that takes an array of promises and returns a single promise that:

● Resolves or rejects as soon as the first promise in the array settles (either resolves or
rejects).

● The returned promise adopts the result or rejection reason of that first settled promise.

Syntax

Promise.race([promise1, promise2, promise3])


.then(result => {
// first promise resolved or rejected
})
.catch(error => {
// first promise rejected
});
Example
const promise1 = new Promise((resolve) => setTimeout(() => resolve('one'), 1000));
const promise2 = new Promise((resolve) => setTimeout(() => resolve('two'), 500));

Promise.race([promise1, promise2])
.then(value => {
console.log(value); // prints "two" because promise2 resolves first after 500ms
});

Fetch API using Promises


fetch('https://jsonplaceholder.typicode.com/comments')
.then(response => response.json())
.then(data => {
document.getElementById('demo').innerText = JSON.stringify(data, null, 2);
})
.catch(err => {
document.getElementById('demo').innerText = 'Error fetching data';
});

—---------------------------------------------------------------------------------------------
//create a html file with <div id=”demo”></div> and call this script in it

fetch1.js

fetch('https://jsonplaceholder.typicode.com/comments')
.then(response => response.json())
.then(data => {
const outputDiv = document.getElementById('demo');
let html = '<h3>Comments:</h3><ul>';
data.forEach(comment => {
html += `<li>
<strong>Post ID:</strong> ${comment.postId},
<strong>Name:</strong> ${comment.name},
<strong>Email:</strong> ${comment.email}
</li>`;
});
html += '</ul>';
outputDiv.innerHTML = html;
})
.catch(err => {
document.getElementById('demo').innerText = 'Error fetching data';
});

—---------
Fetching Multiple APIs

const api1 = fetch('https://jsonplaceholder.typicode.com/posts/1');


const api2 = fetch('https://jsonplaceholder.typicode.com/posts/2');

Promise.all([api1, api2])
.then(responses => Promise.all(responses.map(res => res.json())))
.then(data => {
console.log(data); // array of API results
})
.catch(err => console.log(err));

—----------------
Async and Await

Async Syntax
"async and await make promises easier to write"
async makes a function return a Promise
await makes a function wait for a Promise
The keyword async before a function makes the function return a promise:
Await Syntax
The await keyword can only be used inside an async function.
The await keyword makes the function pause the execution and wait for a resolved promise
before it continues:
let value = await promise;
Example
Basic Syntax
async function myDisplay() {
let myPromise = new Promise(function(resolve, reject) {
resolve("NEC !!");
});
document.getElementById("demo").innerHTML = await myPromise;
}

myDisplay();

async1.js

const posts = [
{title:"One", body:"this is post one"},
{title:"Two", body:"this is post two"}
];
function getPosts(){
setTimeout(()=>{
let output='';
posts.forEach((post,index)=>{
output+=`<li> ${post.title} </li>`;
})
document.body.innerHTML=output;
},1000);
}
function createPost(post){
return new Promise((resolve, reject)=>{
setTimeout(()=>{
posts.push(post);
const error=false;
if(!error)
resolve();
else
reject('Error');
},2000);
});
}
async function init() {
await createPost({title:'Three',body:'post three'});
getPosts();
}
init();
—-------------------------------------------------------------------
async function fetchData() {
try {
let response = await fetch('https://jsonplaceholder.typicode.com/posts');
let data = await response.json();
console.log(data); // Log the data if the fetch is successful
} catch (error) {
console.log("Error fetching data:", error); // Catch and log the error if the fetch fails
}
}
fetchData();

Key Concepts: async and await

● async:
o Marks a function as asynchronous and ensures that the function will return a
Promise.
o An async function always returns a Promise, even if you don't explicitly return
one.
o Does not inherently make the code run in parallel, it just allows the use of
await inside it.
● await:
o Pauses the execution of the async function until the Promise resolves or rejects.
o Does not make the code run in parallel. Instead, it ensures that the async
function waits for the Promise to complete before proceeding to the next line of
code.
o This is sequential behavior, but it makes it look and behave like synchronous
code.

● Sequential Execution with await: When you use await one after another, it causes the
code to run sequentially (one after the other), meaning each asynchronous task waits for
the previous one to finish before starting the next.

Example: Sequential Execution (One Task at a Time)


async function fetchSequential() {
let response1 = await fetch('https://jsonplaceholder.typicode.com/posts/1');
let data1 = await response1.json(); // Waits until the first fetch is completed

let response2 = await fetch('https://jsonplaceholder.typicode.com/posts/2');


let data2 = await response2.json(); // Waits until the second fetch is completed

console.log(data1, data2); // Logs both results after both are fetched


}
fetchSequential();
● Output:

o The second fetch() call waits for the first one to complete.
o This is sequential execution, and each task must finish before the next begins.
● Parallel Execution with Promise.all():
To run multiple asynchronous tasks in parallel, you use Promise.all(), which takes
multiple Promises and waits for all of them to resolve simultaneously.
Example: Parallel Execution with Promise.all()

async function fetchInParallel() {


let [response1, response2] = await Promise.all([
fetch('https://jsonplaceholder.typicode.com/posts/1'),
fetch('https://jsonplaceholder.typicode.com/posts/2')
]);

let data1 = await response1.json();


let data2 = await response2.json();

console.log(data1, data2); // Logs both results after both are fetched


}

fetchInParallel();

● Output:
o Both fetch() calls are initiated at the same time.
o The program waits for both to finish simultaneously (in parallel).
o This is parallel execution.

—---------------------

E-Commerce Order Processing

An e-commerce platform has addToCart(product, callback / promise / async) – adds a product to


the cart (1 sec delay), placeOrder(order, callback / promise / async) – places the order (2 sec
delay), sendConfirmationEmail(order) – sends order confirmation email.

File Upload and Processing


In a document management system uploadFile(file, callback / promise / async) – uploads a file (2
sec delay), processFile(file, callback / promise / async) – processes the uploaded file (3 sec
delay), generateReport(file) – generates a report.

—------------

Web API
API stands for Application Programming Interface.
A Web API is an application programming interface for the Web.
A Browser API can extend the functionality of a web browser.
A Server API can extend the functionality of a web server.

Browser APIs
All browsers have a set of built-in Web APIs to support complex operations, and to help
accessing data.
For example, the Geolocation API can return the coordinates of where the browser is located.

Third Party APIs


Third party APIs are not built into your browser.
To use these APIs, you will have to download the code from the Web.
Examples:
● YouTube API - Allows you to display videos on a web site.
● Twitter API - Allows you to display Tweets on a web site.
● Facebook API - Allows you to display Facebook info on a web site.
Web History API
The Web History API provides easy methods to access the windows.history object.
The window.history object contains the URLs (Web Sites) visited by the user.
The History back() Method
The back() method loads the previous URL in the windows.history list.
It is the same as clicking the "back arrow" in your browser.
Example
<button onclick="myFunction()">Go Back</button>

<script>
function myFunction() {
window.history.back();
}
</script>
The History go() Method
The go() method loads a specific URL from the history list:
Example
<button onclick="myFunction()">Go Back 2 Pages</button>

<script>
function myFunction() {
window.history.go(-2);
}
</script>
History Object Properties

Property Description

length Returns the number of URLs in the history list

History Object Methods

Method Description

back() Loads the previous URL in the history list

forward() Loads the next URL in the history list

go() Loads a specific URL from the history list

Web Storage API


The Web Storage API is a simple syntax for storing and retrieving data in the browser. It is very
easy to use:
Example
localStorage.setItem("name", "John Doe");
localStorage.getItem("name");
The localStorage Object
The localStorage object provides access to a local storage for a particular Web Site. It allows you
to store, read, add, modify, and delete data items for that domain.
The data is stored with no expiration date, and will not be deleted when the browser is closed.
The data will be available for days, weeks, and years.

The setItem() Method


The localStorage.setItem() method stores a data item in a storage.
It takes a name and a value as parameters:
Example
localStorage.setItem("name", "John Doe");

The getItem() Method


The localStorage.getItem() method retrieves a data item from the storage.
It takes a name as parameter:
Example
localStorage.getItem("name");
The sessionStorage Object
The sessionStorage object is identical to the localStorage object. The difference is that the
sessionStorage object stores data for one session. The data is deleted when the browser is closed.

Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
sessionStorage.setItem("name","John Doe");
document.getElementById("demo").innerHTML = sessionStorage.getItem("name");
</script>
</body>
</html>

The setItem() Method


The sessionStorage.setItem() method stores a data item in a storage.

It takes a name and a value as parameters:

Example
sessionStorage.setItem("name", "John Doe");
The getItem() Method
The sessionStorage.getItem() method retrieves a data item from the storage.

It takes a name as parameter:

Example
sessionStorage.getItem("name");
Storage Object Properties and Methods

Web Geolocation API


Locate the User's Position
The HTML Geolocation API is used to get the geographical position of a user.
Since this can compromise privacy, the position is not available unless the user approves it
Using the Geolocation API
The getCurrentPosition() method is used to return the user's position.
The example below returns the latitude and longitude of the user's position:
<!DOCTYPE html>
<html>
<head>
<title>Geolocation Example</title>
</head>
<body>

<h2>Get Your Location</h2>


<button onclick="getLocation()">Get Location</button>

<p id="demo">Click the button to get your location.</p>

<script>
const x = document.getElementById("demo");

function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}

function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}

function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation.";
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable.";
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out.";
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred.";
break;
}
}
</script>

</body>
</html>

JavaScript Fetch API


A Fetch API Example
The example below fetches a file and displays the content:
Example
fetch(file)
.then(x => x.text())
.then(y => myDisplay(y));
Since Fetch is based on async and await, the example above might be easier to understand like
this:
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo">Fetch a file to change this text.</p>

<script>
getText("fetch_info.txt");

async function getText(file) {


let x = await fetch(file);
let y = await x.text();
document.getElementById("demo").innerHTML = y;
}
</script>

</body>
</html>

Image & Video Fetching


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Pexels Photo & Video Fetcher</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
input, button {
padding: 8px;
font-size: 16px;
}
.media-container {
display: flex;
flex-wrap: wrap;
gap: 15px;
margin-top: 20px;
}
img, video {
max-width: 300px;
border-radius: 8px;
}
</style>
</head>
<body>
<h1>Fetch Photos & Videos from Pexels</h1>
<input type="text" id="queryInput" placeholder="Enter keyword (e.g. nature)" />
<button onclick="search()">Search</button>

<div class="media-container" id="photoContainer"></div>


<div class="media-container" id="videoContainer"></div>

<script>
const API_KEY =
"knSNcrSinlDkid0qcBEEBoFeI1Ww5KS7wpotA4hrpFqUPZBk9rXungL5";
const headers = { Authorization: API_KEY };

async function fetchPexelsPhotos(query) {


const url = `https://api.pexels.com/v1/search?query=$
{encodeURIComponent(query)}&per_page=6`;
const response = await fetch(url, { headers });
const data = await response.json();
return data.photos;
}

async function fetchPexelsVideos(query) {


const url = `https://api.pexels.com/videos/search?query=$
{encodeURIComponent(query)}&per_page=4`;
const response = await fetch(url, { headers });
const data = await response.json();
return data.videos;
}

async function search() {


const query = document.getElementById("queryInput").value.trim();
if (!query) return alert("Please enter a keyword!");

const photoContainer = document.getElementById("photoContainer");


const videoContainer = document.getElementById("videoContainer");

photoContainer.innerHTML = "<h2>Loading photos...</h2>";


videoContainer.innerHTML = "<h2>Loading videos...</h2>";

const [photos, videos] = await Promise.all([


fetchPexelsPhotos(query),
fetchPexelsVideos(query),
]);

photoContainer.innerHTML = "<h2>Photos</h2>";
photos.forEach(photo => {
const img = document.createElement("img");
img.src = photo.src.medium;
photoContainer.appendChild(img);
});
videoContainer.innerHTML = "<h2>Videos</h2>";
videos.forEach(video => {
const vid = document.createElement("video");
vid.src = video.video_files[0].link;
vid.controls = true;
videoContainer.appendChild(vid);
});
}
</script>
</body>
</html>
—---------------
Design a simple web page that contains a search box where the user can enter the name of a
country. Upon clicking the "Search" button, the program should fetch and display information
about that country (such as its capital, population, region, flag, etc.) by calling a public API.
—--------------

JavaScript Modules
In JavaScript, modules allow you to split your code into smaller, reusable pieces, which makes it
easier to manage, maintain, and debug. The module system in JavaScript was introduced in ES6
(ECMAScript 2015), and it provides a way to export and import functions, objects, or values
between different files. This system helps in organizing code, avoiding global scope pollution,
and enabling code reuse across different parts of an application.
JavaScript modules allow you to:

1. Export code (variables, functions, classes, objects, etc.) from one module.
2. Import that code into another module to use it.

Module Syntax in JavaScript


JavaScript modules use two key operations:

● Exporting: To make parts of your code available to other files.


● Importing: To use the exported parts in other files.

1. Exporting Code
There are two primary ways to export code in JavaScript modules:

● Named exports: Exporting multiple variables, functions, or objects by name.


● Default exports: Exporting a single variable, function, or object as the default export of
the module.

1.1 Named Exports


Named exports allow you to export multiple bindings from a module, and each export must be
named when importing.
// module1.js
export const name = 'Alice';
export function greet() {
console.log('Hello!');
}
In the example above, both the name variable and the greet function are exported using named
exports.
1.2 Default Exports
A module can only have one default export, and it can be anything: a variable, function, class,
etc.
const greet = () => {
console.log('Hello, this is the default export!');
};
export default greet;
Here, the greet function is the default export. This means when you import from module2.js,
you'll import the function as the default.
2. Importing Code
to use code exported from another module, import it.
2.1 Importing Named Exports
When importing named exports, you need to use the exact name of the export enclosed in curly
braces.
// app.js
import { name, greet } from './module1.js';

console.log(name); // Alice
greet(); // Hello!
In this case, name and greet are named exports from module1.js, so we import them inside curly
braces.
2.2 Importing Default Exports
For default exports, you don't need curly braces, and can name the import whatever you want.
// app.js
import greet from './module2.js';

greet(); // Hello, this is the default export!


Here, the greet function is imported from module2.js, and we can name it anything (it’s
automatically the default export from module2.js).
2.3 Renaming Imports
can also rename imports using the as keyword to avoid naming conflicts.
// module1.js
export const name = 'Alice';
export const age = 25;

// app.js
import { name, age as userAge } from './module1.js';

console.log(name); // Alice
console.log(userAge); // 25
In this example, age is renamed to userAge during the import to avoid potential naming conflicts.
2.4 Importing Everything from a Module
You can import all exports from a module into a single object using * as.
// app.js
import * as myModule from './module1.js';

console.log(myModule.name); // Alice
myModule.greet(); // Hello!
Here, all the named exports from module1.js are imported into the myModule object, and can
access them with myModule.name, myModule.greet(), etc.
3. Module Usage in Browsers and Node.js
3.1 Using Modules in the Browser (ES6 Modules)
To use JavaScript modules in the browser, you need to use the type="module" attribute in the
<script> tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Module Example</title>
</head>
<body>
<script type="module">
import { name, greet } from './module1.js';
console.log(name); // Alice
greet(); // Hello!
</script>
</body>
</html>
In this example:

● The type="module" attribute tells the browser to treat the script as a module.
● Modules are deferred by default, so the script won't block the rendering of the page.

Important: When using modules in the browser, file paths must be relative or absolute URLs
(e.g., ./module1.js), and the JavaScript files must be served from a web server (because browsers
don’t allow loading modules from the file:// protocol for security reasons).
—-------------

Exercises

1. Create math.js exporting: add(a,b) subtract(a,b) multiply(a,b) Import all in main.js and
calculate: add(5,3) subtract(10,4) multiply(2,6) Print the results.
2. products.js Export an array of 3 products: id, name, price. cart.js: Import products array
from products.js. Write a function calculateTotal() to sum prices of all products. Export
this function. main.js: Import calculateTotal() from cart.js and print total value.

3. Write the students.js module with at least 3 students using module.exports. How will you
use the built-in http module in server.js to create a server and display the student list?
Extend students.js to include a function to add a new student, and explain how you will
call it in server.js.

—-----------------

MVC (Model-View-Controller) Architecture in JavaScript

The MVC pattern is a design pattern used to separate the logic of an application into three main
components:
● Model: Handles the data and business logic.
● View: Displays the data to the user.
● Controller: Manages the interaction between the Model and the View.

Let’s go through a simple MVC example in JavaScript. We'll create a small program where a
user can add and view notes. The application will follow the MVC pattern for better structure
and organization.

Step-by-Step Breakdown:

● Model: Manages the data (the notes).


● View: Displays the data (the list of notes) and gets input from the user.
● Controller: Handles the logic and communication between the View and Model.

Simple MVC Example:

<!DOCTYPE html>
<html>
<head>
<title>Simple MVC Example</title>
</head>
<body>

<script>
// Model
class Model {
constructor() {
this.count = 0;
}

increment() {
this.count++;
}

getCount() {
return this.count;
}
}
// View
class View {
constructor() {
this.button = document.createElement('button');
this.button.innerText = "Increment";

this.display = document.createElement('p');
this.display.innerText = "Count: 0";

document.body.appendChild(this.display);
document.body.appendChild(this.button);
}

update(count) {
this.display.innerText = "Count: " + count;
}

bindIncrement(handler) {
this.button.addEventListener('click', handler);
}
}

// Controller
class Controller {
constructor(model, view) {
this.model = model;
this.view = view;

this.view.bindIncrement(this.handleIncrement.bind(this));
}

handleIncrement() {
this.model.increment();
this.view.update(this.model.getCount());
}
}

// Initialize MVC
const appModel = new Model();
const appView = new View();
const appController = new Controller(appModel, appView);

</script>
</body>
</html>

Advantages of MVC:

● Separation of Concerns: The application is divided into distinct layers (Model, View,
Controller) making it easier to maintain and modify.
● Testability: Each component can be tested independently.
● Reusability: The Model and View can be reused in other parts of the application, and the
View can be updated without affecting the logic of the Model.

This is a very simple implementation of the MVC pattern in JavaScript. For more complex
applications, you may need to use frameworks like React, Angular, or Vue.js, which help
structure your code in an even more modular and scalable way.

1. Online Shopping Cart System:

● implement a shopping cart where users can add/remove items, view the total price, and
checkout using the MVC pattern.
● Model manage product data, cart data, and prices while keeping track of available stock
● Controller handle user actions like adding items to the cart or updating quantities, and
how would it interact with the View

2. Blog Application:

● Model handle the creation, deletion, and modification of blog posts, while also managing
categories and tags
● View be designed to display blog posts, categories, and tags, and how should it update
when a user creates, edits, or deletes posts
● Controller facilitate communication between the model and view, allowing users to
submit new posts, delete existing ones, and filter posts by category or tag

3. Task Management (To-Do List) App:

● Model handle task data, including descriptions, due dates, and completion status
● Controller handle the logic for marking tasks as complete, deleting tasks, and filtering
tasks based on status
● View make to show different task statuses, and how can the View allow users to interact
with and modify the tasks

You might also like