CO1 Notes
CO1 Notes
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!
1. camelCase
let myAwesomeVariable
2. snake_case
let my_awesome_variable
Constant variable
const FILE_SIZE_LIMIT = 2000
const MAX_SPEED = 300
console.log(name)
JavaScript Basic Data Types
● Strings
● Numbers
● Booleans
● Null
● Undefined
let name = "John";
let topic = "JavaScript";
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.
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'
if (condition) {
// code to execute if condition is true
}
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");
}
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:
console.log(birds[0]); // Owl
console.log(birds[1]); // Eagle
console.log(birds);
// ['Owl', 'Eagle', 'Vulture', 'Falcon']
let birds = ['Owl', 'Eagle'];
birds.push('Sparrow');
console.log(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'];
console.log(pos); // 2
console.log(fishes.length); // 3
—---------
//remove at specific index
let arr = [5, 10, 15, 20, 25];
ar.splice(index, 0, 18);
Array Iteration:
For loop
let fishes = ['Salmon', 'Goldfish', 'Tuna'];
while loop
let fishes = ['Salmon', 'Goldfish', 'Tuna'];
let i = 0;
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'];
Array Methods:
map()
Purpose
Syntax
array.map((element, index, array) => {
// return new value
});
Example
const numbers = [1, 2, 3, 4];
Purpose
● 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];
console.log(evens); // [2, 4, 6]
reduce()
Purpose
Syntax
array.reduce((accumulator, currentValue, index, array) => {
// return updated accumulator
}, initialValue);
Example: Sum of numbers
const numbers = [1, 2, 3, 4];
console.log(sum); // 10
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];
console.log(result); // 56
Key Differences
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:
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;
● Copies elements from an array or properties from an object into a new array or object.
with arrays
const fruits = ['Apple', 'Blueberry', 'Orange', 'Mango'];
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.
with objects
const person = {
name: 'John Doe',
age: 30,
city: 'New York'
};
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");
greet("sunny");
greet(undefined, "sunny");
Syntax
function () {
// code block
}
greet();
//with parameter
let add = function(a, b) {
return a + b;
};
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!");
};
//with parameter
const greetings = (name) => {
console.log(`Hello, ${name}!`);
};
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:
//no parameter
const greetings = () => console.log("Hello World!");
printArgs(1, 2, 3);
//Uncaught ReferenceError: arguments is not defined
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"]);
console.log(myBook);
result:
{
title: 'JavaScript Introduction',
author: 'Nathan Sebhastian',
year: 2023,
publisher: 'CodeWithNathan'
}
console.log(myBook);
Output:
{
title: 'JavaScript Introduction',
author: 'John Doe'
}
delete myBook.author;
console.log(myBook);
Output:
{ title: 'JavaScript Introduction' }
The currency is assumed in USD, so you don't need to add it to the program.
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:
—--------------------------
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM is a standard object model and programming interface for HTML. It
defines:
In other words: The HTML DOM is a standard for how to get, change, add, or delete
HTML elements.
The HTML DOM can be accessed with JavaScript (and with other programming languages).
A property is a value that you can get or set (like changing the content of 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
Property Description
Method Description
Method Description
Method Description
The easiest way to find an HTML element in the DOM, is by using the element id.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const element = document.getElementsByTagName("p");
</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().
const x = document.getElementsByClassName("intro");
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.
<!DOCTYPE html>
<html>
<body>
<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.
<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>
<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>
<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
<input id="numb">
<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>
<html>
<body>
<script>
document.getElementById("p2").style.color = "blue";
</script>
</body>
</html>
//chnaging the text color to Red
<!DOCTYPE html>
<html>
<body>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
</body>
</html>
JavaScript HTML DOM Events
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>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
displayDate()
setInterval(displayDate,1000);
</script>
<p id="demo"></p>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<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()">
<p id="demo"></p>
<script>
function checkCookies() {
if (navigator.cookieEnabled == true) {
} else {
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
function upperCase() {
const x = document.getElementById("fname");
x.value = x.value.toUpperCase();
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<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>
style="background-color:#D94A38;width:120px;height:20px;padding:40px;">
<script>
function mOver(obj) {
function mOut(obj) {
</script>
</body>
</html>
//onmousedown and up
<!DOCTYPE html>
<html>
<body>
Click Me</div>
<script>
function mDown(obj) {
obj.style.backgroundColor = "red";
function mUp(obj) {
obj.style.backgroundColor="green";
obj.innerHTML="Thank You";
</script>
</body>
</html>
JavaScript HTML DOM EventListener
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 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>
<p id="demo"></p>
<script>
document.getElementById("myBtn").addEventListener("click", displayDate);
function displayDate() {
document.getElementById("demo").innerHTML = Date();
</script>
</body>
</html>
—--------------
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<script>
document.getElementById("myBtn").addEventListener("click", function() {
alert("Hello World!");
});
</script>
</body>
</html>
—--------
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<script>
var x = document.getElementById("myBtn");
x.addEventListener("click", myFunction);
x.addEventListener("click", someOtherFunction);
function myFunction() {
}
function someOtherFunction() {
</script>
</body>
</html>
—--------
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 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>
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:
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;
padding: 20px;
</style>
</head>
<body>
<h2>JavaScript addEventListener()</h2>
<div id="myDiv1">
<h2>Bubbling:</h2>
</div><br>
<div id="myDiv2">
<h2>Capturing:</h2>
<p id="myP2">Click me!</p>
</div>
<script>
document.getElementById("myP1").addEventListener("click", function() {
}, false);
document.getElementById("myDiv1").addEventListener("click", function() {
}, false);
document.getElementById("myP2").addEventListener("click", function() {
}, true);
document.getElementById("myDiv2").addEventListener("click", function() {
}, true);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
background-color: coral;
padding: 50px;
color: white;
font-size: 20px;
</style>
</head>
<body>
<h2>JavaScript removeEventListener()</h2>
<div id="myDIV">
</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
<script>
document.getElementById("id02").innerHTML =
document.getElementById("id01").innerHTML;
</script>
</body>
</html>
Example
<html>
<body>
<script>
document.getElementById("id02").innerHTML =
document.getElementById("id01").firstChild.nodeValue;
</script>
</body>
</html>
Example
<html>
<body>
<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.
<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
<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);
<script>
const para = document.createElement("p");
const node = document.createTextNode("This is new.");
para.appendChild(node);
—---------------
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>
<script>
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
myCalculator(5, 5);
</script>
</body>
</html>
—-------------
Callback in JavaScript
A callback is:
● It is “called back” inside the outer function to complete some action or logic.
In simple words:
<html>
<body>
<h1>JavaScript Functions</h1>
<h2>Callback Functions</h2>
<p id="demo"></p>
<script>
function myDisplayer(something) {
document.getElementById("demo").innerHTML = something;
myCallback(sum);
myCalculator(5, 5, myDisplayer);
</script>
</body>
</html>
● 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();
—-------------------
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);
}
getPosts();
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)
When Call
myPromise.state myPromise.result
"pending" undefined
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();
—----------
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.
Example
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])
.then(value => {
console.log(value); // prints "two" because promise2 resolves first after 500ms
});
—---------------------------------------------------------------------------------------------
//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
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();
● 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.
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()
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.
—---------------------
—------------
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.
<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
Method Description
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>
Example
sessionStorage.setItem("name", "John Doe");
The getItem() Method
The sessionStorage.getItem() method retrieves a data item from the storage.
Example
sessionStorage.getItem("name");
Storage Object Properties and Methods
<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>
<script>
getText("fetch_info.txt");
</body>
</html>
<script>
const API_KEY =
"knSNcrSinlDkid0qcBEEBoFeI1Ww5KS7wpotA4hrpFqUPZBk9rXungL5";
const headers = { Authorization: API_KEY };
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.
1. Exporting Code
There are two primary ways to export code in JavaScript modules:
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';
// 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.
—-----------------
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:
<!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.
● 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
● 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