javaScriptManual2 (AutoRecovered)
javaScriptManual2 (AutoRecovered)
Table of Contents
CHAPTER 1..............................................................................................................................................6
Introduction to JavaScript....................................................................................................................6
Brief History of JavaScript..................................................................................................................6
Requirements to Learning JavaScript..................................................................................................7
CHAPTER 2................................................................................................................................................8
Setting Up Your JavaScript Environment................................................................................................8
Running JavaScript on Browser.......................................................................................................8
JavaScript embed code............................................................................................................................8
Inline JavaScript................................................................................................................................9
Internal JavaScript............................................................................................................................9
External JavaScript.........................................................................................................................11
CHAPTER 3............................................................................................................................................12
JavaScript Statements............................................................................................................................12
JavaScript Comments.....................................................................................................................12
Variables............................................................................................................................................13
Variable naming rules........................................................................................................................14
CHAPTER 4............................................................................................................................................16
Data Types.............................................................................................................................................16
Primitive data type.............................................................................................................................16
Operation on Primitive Data type..........................................................................................................19
Arithmetic Operators (Number).........................................................................................................21
Comparison Operators (All data type)...............................................................................................23
Logical Operators (Boolean).............................................................................................................26
CHAPTER 5............................................................................................................................................28
Making Decision by Conditional statements.........................................................................................28
IF statement.......................................................................................................................................28
IF and ELSE statement......................................................................................................................29
IF…ELSE IF statement.....................................................................................................................29
SWITCH Statement...........................................................................................................................30
CHAPTER 6............................................................................................................................................32
LOOPS..................................................................................................................................................32
Why do will need Loop?....................................................................................................................32
WHILE Loops...................................................................................................................................32
DO WHILE LOOP............................................................................................................................33
FOR Loops........................................................................................................................................34
Break statement.................................................................................................................................36
Continue statement............................................................................................................................36
CHAPTER 7..............................................................................................................................................38
Function.................................................................................................................................................38
Function declaration and expression..................................................................................................38
Function expression.........................................................................................................................39
Parameters and Arguments................................................................................................................39
Function Return.................................................................................................................................40
Callback Functions............................................................................................................................41
Arrow Functions................................................................................................................................42
Scope.................................................................................................................................................43
CHAPTER 8............................................................................................................................................46
Array.....................................................................................................................................................46
CLASS ACTIVES...........................................................................................................................................48
CHAPTER 9............................................................................................................................................50
OBJECT................................................................................................................................................50
Object Properties...............................................................................................................................51
CHAPTER 10............................................................................................................................................60
Properties and Methods.........................................................................................................................60
String Properties and Methods...........................................................................................................60
Number methods...............................................................................................................................64
Array Properties and Methods...........................................................................................................64
Array Iteration.................................................................................................................................70
CHAPTER 11..........................................................................................................................................75
CLASSES..............................................................................................................................................75
constructor.........................................................................................................................................75
Methods.............................................................................................................................................76
Getters and Setters.............................................................................................................................77
Class inheritance................................................................................................................................78
CHAPTER 12..........................................................................................................................................81
Date Objects and Math Objects.............................................................................................................81
Date object.........................................................................................................................................81
Math Object.....................................................................................................................................81
CHAPTER 13..........................................................................................................................................85
Window Object......................................................................................................................................85
What is Window Object.....................................................................................................................85
CHAPTER 14..........................................................................................................................................89
Introduction to Document Object Model (DOM)..................................................................................89
What is the DOM?.............................................................................................................................89
How to Select Elements in the Document..........................................................................................90
CHAPTER 15......................................................................................................................................97
Traversing the DOM..............................................................................................................................97
Using the children or childNodes Properties......................................................................................97
lastChild and firstChild Properties.....................................................................................................99
parentElement or parentNode............................................................................................................99
nextElementSibling or previousElementSibling............................................................................99
CHAPTER 16..........................................................................................................................................101
DOM Styling – Applying Styling With CSS............................................................................................101
CHAPTER 17..........................................................................................................................................105
DOM Manipulation.............................................................................................................................105
ClassName and ClassList................................................................................................................106
contains............................................................................................................................................108
Creating Elements...........................................................................................................................108
Creating TextNode..........................................................................................................................108
Append Child..................................................................................................................................109
AppendChild...................................................................................................................................110
Remove............................................................................................................................................111
removeChild....................................................................................................................................112
setAttribute......................................................................................................................................113
removeAttribute...............................................................................................................................114
InnerHTML, InnerText and TextContent........................................................................................114
CHAPTER 18..........................................................................................................................................116
Events..................................................................................................................................................116
onclick Event Type..........................................................................................................................116
onsubmit Event Type...........................................................................................................................117
Form Events....................................................................................................................................123
Form Validation.................................................................................................................................128
CHAPTER 19........................................................................................................................................131
Local Storage in JavaScript.................................................................................................................131
CHAPTER 20..........................................................................................................................................134
HTMLElement: Dataset Property........................................................................................................134
CHAPTER 21..........................................................................................................................................136
Asynchronous JavaScript.................................................................................................................136
CHAPTER 1
Introduction to JavaScript
JavaScript is the world's most popular programming language. JavaScript is the
programming language of the Web.
You can work as a frontend developer, backend developer and also as a full-stack
developer with JavaScript.
For a very long JavaScript was only used in the browser to build interactive web pages
but those days are gone due to heavy investment from big companies like Google.
Nowadays you can build full grown web/mobile applications, real-time networking
applications, games, etc.
JavaScript was originally designed to run on browsers. That means every browser has a
JavaScript engine used to execute JavaScript code. For example, the JavaScript engine
for Firefox is Spider-Monkey while that of Chrome is the V8 engine.
In 2009, the JavaScript engine in Chrome was embedded inside a C++ program, and was
called Node. So, Node is a C++ program that includes Google Chrome V8 engine. We
can also say Node is a JavaScript runtime built on Chrome's V8 JavaScript engine. Now
with this we can run JavaScript program outside of a browser. We can pass JavaScript
codes into Node, that means we can build backend applications like web and mobile
apps.
In a nutshell, JavaScript code can be run inside of a browser or in a terminal (Node).
Browser and Node provides a run-time environment for our JavaScript code.
console.log("Hello World!");
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="alert('Hello world')">Click Me</button>
</body>
</html>
Internal JavaScript
JavaScript can be added directly to the HTML file by writing the code inside the
<script> tag. We can place the <script> tag inside the <body> tag according to the need.
Its separate HTML and JavaScript code. It makes HTML and JavaScript easier to read
and maintain. It is rarely used for multiple pages.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>Welcome to JavaScript</h1>
<script>
console.log("hello world!");
</script>
</body>
</html>
Note: When you place your JavaScript at the bottom of your HTML body, it gives the
HTML time to load before any of the JavaScript loads, which can prevent errors, and
speed up website response time.
External JavaScript
JavaScript can also be placed in external files. To use an external script, put the name of
the script file in the src (source) attribute of a <script> tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Hello World!</h1>
<script src="hello.js"></script>
</body>
</html>
JavaScript Outputs
JavaScript can "display" data in different ways:
Writing into the browser console, using console.log()
console.log("hello world!");
CHAPTER 3
JavaScript Statements
A JavaScript program is made up of a series of statements. These statements contain
JavaScript language construct, keyword and command. Each statement ends with a new
line or semicolon. But a popular convention adopted by JavaScript programmer is to
write one statement per line and end the line with a semi colon.
document.write("Hello World");
document.write("Here come the JS Engineer");
JavaScript Comments
Comments are human-readable texts ignored by the computer. There are two types of
comment in JavaScript:
let myName = "janet"; // declaring the variable name and put data inside the
variable
console.log(myName); // get the data inside the variable
let name = "Seyi";
name = "Janet";
console.log(name);
If you noticed the “name” variable above was reassigned another value (from Seyi to
Janet)
const PI = 3.14;
PI = 9.8;
console.log(PI);
Variables are usually given a name so that it is easy to differentiate them. There are some
rules that must be followed when giving variable name.
String data type: A string is a collection of letters and symbols enclosed within
quote mark. The quote mark can either be single or double. If you want to use
double quote marks inside the string, you need to use single quote marks to
enclose the string. And if you want to use an apostrophe in your string, you need
to employ double quote marks to enclose the string.
Examples.
You can use quotes inside a string, as long as they don't match the quotes surrounding the
string:
289; //integer
45.6; //float
1e6; // means 1 multiplied by 10 to the power 6 (a million)
2E3; // can also be written as 2E3, 2E+3 and 2e+3
NaN; //usually call Not a Number
let myScore=87; //assigning an integer to a variabl
true;
false;
let isRich=true; //assigning boolean into a variable
let amLearningCSS=false; //assigning boolean into a variable
undefined;
null;
let justAVariable; //the value of this value before any assignment is undefined
Operation on Primitive Data type
Concatenation Operators (String)
The only operation that can be performed on string data type is concatenation. The
operation simply joins two strings data and produces another string which composes both
strings. To concatenate a string, you add a plus sign+ between the strings or string
variables you want to connect.
Example:
let partSentenceOne = "This is a ";
let partSentenceTwo = "complete sentence";
let output = partSentenceOne + partSentenceTwo
Template Literals
Template literals (template strings) allow you to use strings or embedded
expressions in the form of a string. They are enclosed in backticks (``).
You can use Template Literals (which was introduced in ES6).
Example:
const name = "Jack";
console.log(`Hello ${name}!`); // Hello Jack!
// Normal concatenation
console.log(name + " works at " + companyName);
// Template Literals
console.log(`${name} works at ${companyName}`);
Noted: JavaScript is loosely typed, meaning you don’t have to tell it the data type
of a certain variable being declared unlike Java or C++. Because of this it will try helping
you out in what we called implicit type conversion.
Arithmetic Operators (Number)
Examples:
+ Operator: The addition operator (+) adds numbers:
let x = 5;
let y = 2;
let z = x + y; //output: 5
let x = 5;
let y = 2;
let z = x - y; //output: 3
let x = 5;
let y = 2;
let z = x / y; //output :2.5
let x = 5;
let y = 2;
let z = x % y; //output :1
let x = 5;
x++;
let z = x; //output :6
let x = 5;
x--;
let z = x; //output :4
** Operator: The exponentiation operator (**) raises the first operand to the power
of the second operand.
let x = 5;
let z = x ** 2; //output :25
let x = 10;
x += 5; //output :15
Examples:
== Operator: Equal to
let x = 5;
x == 5; // This will return true
let x = 5;
x != 8; // This will return true
let x = 5;
x === 5; // This will return true
let x = 5;
let x = 5;
let x = 5;
Logical operators are used to test for true or false. These are typically used in
combination with the comparison operators:
Logical Operator Description
&& Logical and
|| Logical or
! Logical not
Examples:
&& Logical AND Operator:
let x = 6;
let y = 3;
let z = x < 10 && y > 1 //This will return true
|| Logical OR Operator:
x = 6;
let y = 3;
let z = x == 5 || y == 5 // This will return false
let x = 6;
let y = 3;
let z = !(x==y) // This will return true
QUARTERLY TEST
1. JavaScript was originally designed to run on browsers. True or False
2. What is the JavaScript engine for Chrome called?
3. JavaScript code can be run inside a terminal. True or False
4. JavaScript was invented by who?
5. The external JavaScript file must contain the <script> tag. True or False
6. List five JavaScript frameworks / libraries you know
7. State two advantages of embedding JavaScript codes externally compared to inline
8. What is the advantage of using “console.log()” in outputting data in JavaScript
over “alert()” and “document.write()”
9. Inside which HTML element do we put the JavaScript?
10. Differentiate between a single-line comment and a multiple-line comment
11. What is the difference between a “let” keyword and a “const” keyword
12. State any four variable naming rule you know
13. State 4 primitive data types in JavaScript
14. Write a simple program to multiply three numbers
15. Write a simple program to calculate the area of a triangle
16. Write a simple program to calculate the simple interest of a given amount of
money
17. What is the function of the modulus arithmetic operator?
18. Let = 10; x === “10” will return _______
19. Let x = 5; x !== 5 will return ________
20. Let x = 5; x >= 8 will return _________
21. Let x = 6; let y = 5; z = !(x==y) will return _______
22. What is this symbol “&&” called in JavaScript?
CHAPTER 5
Making Decision by Conditional statements
The conditional statements included in the JavaScript code assist with decision making,
based on certain conditions. The condition specified in the conditional statement can
either be true or false. The conditional statements execute the associated piece of code
only if the condition is true. We have four types of conditional statements in JavaScript:
1. An if statement executes a specified code segment if the given condition is ''true.''
2. An else statement executes the code associated with the else if the given if condition
is ''false.''
3. An else if statement specifies a new condition for testing when the first if condition is
''false.''
4. A switch-case statement specifies multiple alternative code blocks for execution and
executes these cases based on certain conditions.
IF statement
IF statement is used specify a block of code to be executed, if a specified condition is
true.
Syntax of the if statement.
if (condition) {
// code to run if condition is true
}
Example:
const age = 12;
if (age < 18) {
console.log("Sorry, you are not old enough to play");
}
IF and ELSE statement
Use else to specify a block of code to be executed, if the same condition is false.
Example:
IF…ELSE IF statement
Use else if to specify a new condition to test, if the first condition is false Code:
Example:
Ternary Operator
This is an alternative way or shorthand in writing the if …else statement.
SWITCH Statement
Use the switch statement to select one of many code blocks to be executed.
Syntax:
switch (expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Examples:
WHILE Loop
The while loop loops through a block of code as long as a specified condition is true.
Syntax
while (condition) {
// code block to be executed
}
Example:
// while loop
let i = 1;
let n = 5;
while (i <= n) {
console.log(i);
i += 1;
}
Output:
1
2
3
4
5
Note: If you forget to increase the variable used in the condition, the loop will never end.
This will crash your browser.
DO WHILE LOOP
The do while loop is a variant of the while loop. This loop will execute the code block
once, before checking if the condition is true, then it will repeat the loop as long as the
condition is true.
Syntax
do {
// code block to be executed
} while (condition);
Example:
// do while loop
let i = 0;
do {
i++;
console.log("This is number " + i);
} while (i <= 5);
Output:
This is number 1
This is number 2
This is number 3
This is number 4
This is number 5
This is number 6
FOR Loops
For loop loops through a block of code a number of times.
The syntax:
Start (Initialization): - This expression runs before the execution of the first loop, and is
usually used to create a counter.
Stop Condition: - This expression is checked each time before the loop runs. If it
evaluates to true, the statement or code in the loop is executed. If it evaluates to false, the
loop stops. And if this expression is omitted, it automatically evaluates to true.
Move: - This expression is executed after each iteration of the loop. This is usually used
to increment a counter, but can be used to decrement a counter instead.
Example:
Output:
0
1
2
3
4
5
6
7
8
9
10
Stop Condition: - Defines the condition for the loop to run (i must be less than or equal
to 10).
Move: - Increases a value (i++) each time the code block in the loop has been executed.
Output:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
Break statement
The break statement breaks out of a switch or a loop. In a switch, it breaks out of the
switch block. This stops the execution of more code inside the switch. In in a loop, it
breaks out of the loop and continues executing the code after the loop (if any).
Example:
Output:
0
1
2
i is equal to 3
Continue statement
The continue statement breaks one iteration (in the loop) if a specified condition occurs,
and continues with the next iteration in the loop.
The difference between continue and the break statement, is instead of "jumping out" of a
loop, the continue statement "jumps over" one iteration in the loop.
if (condition) {
continue;
}
Output:
0
1
2
4
Note: The continue statement is triggered when i equals 3. As a result, the console.log(i)
statement is skipped for that iteration, and the loop moves on to the next iteration
Example:
Note: continue statement will any number that meet the condition statement.
Output:
1 is odd number
3 is odd number
5 is odd number
7 is odd number
9 is odd number
CHAPTER 7
Function
A JavaScript function is a block of code designed to perform a particular task. A function
is executed when "something" invokes it (calls it).
Function names can contain letters, digits, underscores, and dollar signs.
Why Functions?
You can reuse code: Define the code once, and use it many times. You can use the same
code many times with different arguments, to produce different results.
Examples:
function people() {
console.log("Hello world!");
}
// Invoke the function
people();
Examples:
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
Examples:
Function Return
When JavaScript reaches a return statement, the function will stop executing.
Functions often compute a return value. The return value is "returned" back to the
"caller":
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
Default parameter: You can set a default parameter for your function
// Default parameter
function people(name = "Janet", job = "Software Developer") {
console.log("My name is " + name + " " + "I am a " + job);
}
// Invoke the function
people();
Callback Functions
A callback function is a function passed into another function as an argument, which is
then invoked inside the outer function to complete some kind of routine or action.
In JavaScript, you can also pass a function as an argument to a function. This function
that is passed as an argument inside of another function is called a callback function.
// callback function
function callMe() {
console.log("I am callback function");
}
// function
function greet(name, callback) {
console.log("Hi" + " " + name);
callback();
}
Output:
Hi Peter
I am callback function
In the above program, there are two functions. While calling the greet() function, two
arguments (a string value and a function) are passed.
The callMe() function is a callback function.
Note: The callback function is helpful when you have to wait for a result that takes time.
For example, the data coming from a server because it takes time for data to arrive.
Arrow Functions
Arrow functions allows a short syntax for writing function expressions. You don't need
the function keyword, the return keyword, and the curly brackets. Arrow functions can
be identified by the arrow symbol, => that gives them their name.
Examples:
// A function expression
let mult = function (x, y) {
return x * y;
};
// Arrow function
It gets shorter! If the function has only one statement, and the statement returns a value,
you can remove the brackets and the return keyword:
Scope
Scope is an important concept in programming. It refers to where a constant or variable is
accessible by the program. Using const and let to declare variables means they are block
scoped, so their value only exists inside the block they are declared in.
What is a block scope? A block scope is the area within if, switch conditions or for and
while loops. Generally speaking, whenever you see {curly brackets}, it is a block. In
ES6, const and let keywords allow developers to declare variables in the block scope,
which means those variables, exist only within the corresponding block. There are two
types of scope in programs, which are; Global and Local scope.
1. Global Scope: Any variable declared outside of a block is said to have global scope.
This means it is accessible everywhere in the program.
// Global scope
function title() {
console.log(`I love ${course}`);
}
title();
The variable “course” is a global scope variable because it can be accessed anywhere
within the program
2. Local Scope: This means that any variables defined inside a block using the let or
const will only be available inside that block and not be accessible outside of that block.
// Local scope
However, what if you want to loop through the cars and find a specific one? And what if
you had not 3 cars, but 300?
An array can hold many values under a single name, and you can access the values by
referring to an index number.
let quizQuestions = [ ];
Multidimensional array
Arrays can be nested, meaning that an array can contain another array as an element.
let quizQuestions = [
["What is the capital of Lagos State?", "Ikeja", "Agege", "Mushin", "Ikeja"],
[
"What is the capital of Kaduna State?",
"Kagoro",
"Kachia",
"Kaduna",
"Kaduna",
],
];
Spread Operator: The JavaScript spread operator (...) allows us to quickly copy all or
part of an existing array or object into another array or object. It uses the three dots
notation (…)
Example:
//Output 1,2,3,4,5,6
CLASS ACTIVES
1. Used Multidimensional array to create product items.
2. Used spread operator to add another product items to question 1.
3. What is the benefits of using arrays?
const object_name = {
key1: value1,
key2: value2,
};
Here, an object object_name is defined. Each member of an object is a key: value pair
separated by commas and enclosed in curly braces {}.
// object
const student = {
firstName: "ram",
age: 10,
};
Here, student is an object that stores values such as strings and numbers.
// object creation
const person = {
name: "John",
age: 20,
};
console.log(typeof person); // object
In the above example, name and age are keys, and John and 20 are values respectively.
Object Properties
In JavaScript, "key: value" pairs are called properties. For example,
let person = {
name: "John",
age: 20,
};
objectName.key;
Example:
const person = {
name: "John",
age: 20,
};
// accessing property
console.log(person.name); // John
2. Using bracket Notation
Here is the syntax of the bracket notation.
objectName["propertyName"];
Example:
const person = {
name: "John",
age: 20,
};
// accessing property
console.log(person["name"]); // John
// nested object
const student = {
name: "John",
age: 20,
marks: {
science: 70,
math: 75,
},
};
In the above example, an object student contains an object value in the mark’s property.
const person = {
name: "Sam",
age: 30,
// using function as a value
greet: function () {
console.log("hello");
},
};
person.greet(); // hello
Here, a function is used as a value for the greet key. That's why we need to
use person.greet() instead of person.greet to call the function inside the object.
In JavaScript, objects can also contain functions. For example,
const person = {
name: "John",
age: 30,
person.greet();
Output
In the above example, a person object is created. It contains properties (name and age)
and a method greet.
In the method greet, while accessing a property of an object, this keyword is used.
In order to access the properties of an object, this keyword is used following by. and key.
However, the function inside of an object can access it's variable in a similar way as a
normal function would.
For example,
const person = {
name: "John",
age: 30,
greet: function () {
let surname = "Doe";
console.log("The name is" + " " + this.name + " " + surname);
},
};
person.greet();
Output
let human = {
name: "janet",
"firstname lastname": "Miss janet",
greet: (p) => {
return `Hello ${p}!`;
},
};
console.log(human.greet("janet"));
console.log(name); // Sara
console.log(age); // 25
console.log(gender); // female
// destructuring assignment
let { name, age, gender } = person;
console.log(name); // Sara
console.log(age); // 25
console.log(gender); // female
console.log(product[0].name);
console.log(product[0].price);
console.log(
`You order for: ${product[0].name} and price: #${product[0].price}`
);
Let use for loop to loops through the products data.
for (let i = 0;i < product.length; i++) {
console.log(product[i].name);
QUARTERLY TEST
1. Why do we use functions in JavaScript?
2. Create a function that will calculate the price of a given product
3. Create a function, pass two parameters to it and then return the product of the
parameters passed
4. Debug the code below.
people();
9. Write a program to determine the number of students that fail or pass an exam.
The pass mark is 50.
11. Write a program to display multiplication time table for (2x) only. E.g., 2 x 1 = 2, 2
x2=4
const student = {
name: "John",
age: 25,
department: "Computer science",
};
1. How can you get the value of “department” from the object above?
13. Create a products store that will contain price, name, category. Use Array of an
object to create it.
14. Loop through the products store and display the product on console.log. Using for
loop.
CHAPTER 10
Properties and Methods
String Properties and Methods
In JavaScript, strings are considered primitive data types. However, JavaScript provides several built-in
methods and properties that allow you to handle strings as objects. When you use these methods or
properties on a string, JavaScript temporarily wraps the string primitive with a String object, allowing you
to access its functionalities. Below are some inbuilt string properties and methods.
Example:
Example:
Example:
4. startsWith(): To know the starting character. This returns Boolean (true or false)
Example:
const products = [
{
id: 1,
name: "black bag",
price: 500,
description:
"Lorem ipsum dolor sit, amet consectetur adipisicing elit. Minim.",
},
{
id: 2,
name: "shoe",
price: 400,
description:
"Lorem ipsum dolor sit, amet consectetur adipisicing elit. Minim.",
},
{
id: 3,
name: "laptop",
price: 400000,
description:
"Lorem ipsum dolor sit, amet consectetur adipisicing elit. Minim.",
},
{
id: 4,
name: "Hp laptop",
price: 500000,
description:
"Lorem ipsum dolor sit, amet consectetur adipisicing elit. Minim.",
},
{
id: 5,
name: "bag",
price: 500,
description:
"Lorem ipsum dolor sit, amet consectetur adipisicing elit. Minim.",
},
];
function renderProduct(product) {
for (let i = 0; i < products.length; i++) {
if (products[i].name.startsWith(product)) {
console.log(products[i].name);
} else {
console.log("no product!");
}
}
}
renderProduct("b");
5. endsWith(): To know the end character. This returns Boolean (true or false)
Example:
6. indexOf(): The indexOf() method returns the position of the first occurrence of
a value in a string. The indexOf() method returns -1 if the value is not found. The
indexOf() method is case sensitive.
Example:
7. lastIndexOf() : To return the last string of the index you are searching for
Example:
8. slice(): This extracts a part of a string and returns the extracted part in a new
string. The method takes 2 parameters: start position, and end position (end not
included).
Example:
Example:
replace(): The replace() method replaces a specified value with another value in a string:
Example:
10. trim() : The trim() method removes whitespace from both sides of a string.
Example:
11. charAt(): The charAt() method returns the character at a specified index (position)
in a string.
Example:
Example:
Number methods
In JavaScript, numbers can be handled as objects due to the language's ability to automatically
wrap primitive values, such as numbers, in their corresponding object wrapper types. This
process is known as autoboxing or autowrapping.
toFixed(): The toFixed() will define the number of characters after the decimal.
Example:
let y = 8.0873;
console.log(y.toFixed(2));
Example:
let y = 8.0873;
let val = y.toString();
console.log(typeof val);
parseInt(): parseInt() parses a string and returns a whole number. Spaces are allowed.
Only the first number is returned.
Example:
console.log(parseInt("-10"));
console.log(parseInt("10"));
console.log(parseInt("10.33"));
1.Length: - In JavaScript, the length property is used to retrieve the number of elements in an
array. It is a built-in property of the Array object and provides a convenient way to access the
size or length of an array.
let number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
console.log(number.length);
//output: 12
1. Popping and Pushing: When you work with arrays, it is easy to remove elements
and add new elements. This is what popping and pushing is:
Popping items out of an array, or pushing items into an array.
pop(): The pop() method removes the last element from an array:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();
push(): The push() method adds a new element to an array (at the end):
Example
output:4
The first parameter (2) defines the position where new elements should
be added (spliced in).
The second parameter (0) defines how many elements should be removed.
The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.
slice(): The slice() method slices out a piece of an array into a new array.
This example slices out a part of an array starting from array element 1 ("Orange"):
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1);
console.log(citrus);
The slice() method does not remove any elements from the source array.
Note: For numbers the sort will convert the elements to strings. However, if numbers are
sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".
Because of this, the sort() method will produce incorrect result when sorting numbers.
Reversing an Array:
The reverse() method reverses the elements in an array. You can use it to sort an
array in descending order:
Example:
Include in Array:
The includes() method determines whether an array includes a certain value
among its entries, returning true or false as appropriate.
Example:
Join(): The join() method returns an array as a string. The join() method does not
change the original array. Any separator can be specified. The default is comma.
Example:
Array Iteration
Array iteration methods operate on every array item.
forEach(): The forEach() method calls a function (a callback function) once for each
array element. The forEach() does not return a new array.
Example:
cars.forEach(function (car) {
console.log("I love " + car);
});
map (): The map() method creates a new array by performing a function on each array
element. The map() method does not change the original array.
Example
function renderProduct() {
products.map((product) => {
console.log(product.name);
});
}
renderProduct();
filter(): The filter() is an inbuilt method, this method creates a new array with elements
that follow or pass the given criteria and condition.
Example:
console.log(filteredCar);
const grades = ["A", "F", "D", "A", "B", "E", "B", "E", "B", "C"];
const passGrades = grades.filter(function (grade) {
let passGrade = ["A", "B", "C"];
if (passGrade.includes(grade)) {
return grade;
}
});
console.log(passGrades);
function filterProduct(category) {
const productFilter = products.filter(function (product) {
return product.category === category;
});
console.log(productFilter);
}
filterProduct("men");
find(): To find elements in an array you use find(). It will return the first element being
searched in an array.
Example:
function singleProduct(id) {
const displaysingleProduct = products.find((product) => {
return product.id === id;
});
console.log(displaysingleProduct);
}
singleProduct(1);
every(): The every() method checks if all array values pass a test. It returns truthy if the
callback returns true.
Example:
some(): The some() method checks if some array values pass a test. It returns truthy if
the callback returns true.
Example:
indexOf(): The indexOf() method searches an array for an element value and returns
its position.
Example:
QUARTERLY TEST
1. What JavaScript method we I used to returned the last letter of a sentence?
2. Write a program to extract “ola” from the word “interpolation” and concatenate it
with the word “love programming”
3. What is the difference between a slice and a substring?
4. What method can you use to remove whitespace on JavaScript?
5. Write a program that will make the first two characters of the word “angular” to be
in uppercase.
6. What is parseInt used for?
7. Differentiate between pop() and push()
Use the array below to answer question 8 - 11
// creating a class
class Person {
constructor(name) {
this.name = name;
}
}
The class keyword is used to create a class. The properties are assigned in a constructor
function.
constructor
The constructor method is a special method of a class for creating and initializing an
object instance of that class.
A constructor enables you to provide any custom initialization that must be done before
any other methods can be called on an instantiated object.
In JavaScript, the this keyword refers to an object.
The new keyword is used in JavaScript to create a object from a constructor function.
The new keyword has to be placed before the constructor function call and will do the
following things: Creates a new object. Sets the prototype of this object to the constructor
function's prototype property.
// creating a class
class Person {
constructor(name) {
this.name = name;
}
}
// creating an object
const person1 = new Person("John");
const person2 = new Person("Jack");
console.log(person1.name); // John
console.log(person2.name); // Jack
Methods
It is easy to define methods in the JavaScript class. You simply give the name of the
method followed by ().
For example,
class Person {
constructor(name) {
this.name = name;
}
// defining method
greet() {
console.log(`Hello ${this.name}`);
}
}
// accessing property
console.log(person1.name); // John
// accessing method
person1.greet(); // Hello John
Note: To access the method of an object, you need to call the method using its name
followed by ().
class Person {
constructor(name) {
this.name = name;
}
// getter
get personName() {
return this.name;
}
// setter
set personName(x) {
this.name = x;
}
}
Class inheritance
Inheritance enables you to define a class that takes all the functionality from a parent
class and allows you to add more.
Using class inheritance, a class can inherit all the methods and properties of another class.
Inheritance is a useful feature that allows code reusability.
To use class inheritance, you use the extends keyword.
For example:
// parent class
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello ${this.name}`);
}
}
In the above example, the Student class inherits all the methods and properties of
the Person class. Hence, the Student class will now have the name property and
the greet() method.
JavaScript Super() Keyword
The super keyword used inside a child class denotes its parent class.
For example,
// parent class
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello ${this.name}`);
}
}
// inheriting parent class
class Student extends Person {
constructor(name) {
console.log("Creating student class");
Here, super inside Student class refers to the Person class. Hence, when the constructor
of Student class is called, it also calls the constructor of the Person class which assigns a
name property to it.
CHAPTER 12
Date Objects and Math Objects
Date object
Date objects hold information about dates and times. A constructor function is used to
create a new date object using the new operator. Get today’s time
If an argument is not supplied, the date will default to the current date and time. The
parmeters that can be provided are as follows:
New Date(year, month, day, hour, minutes, seconds, milliseconds).
Getting Methods
getDate(): This is used to find the day of the week. It returns a number starting from
zero(0) i.e Sunday will return 0, Monday will return 1 etc.
getMonth(): tis returns an integer starting from zero(0) i.e January is 0, Febuary is 1 etc
Math Object
The JavaScript math object provides several constants and methods to perform
mathematical operation. Unlike date object, it doesn't have constructors.
The JavaScript Math object allows you to perform mathematical tasks on number.
Math methods
Mathematics plays an integral part in computer science and coding. Programmers use
mathematical methods and expressions to perform calculations for all sorts of different
reasons during development. Luckily, JavaScript provides various built-in methods that
can make your life a whole lot easier.
1. Math.abs() : The abs() method returns the absolute value of a number.
Example:
2. Math.round(): The round() method returns the value of a number rounded to the
nearest integer.
Example:
console.log(Math.round(num1));
console.log(Math.round(num2));
console.log(Math.round(num3));
console.log(Math.round(num4));
3. Math.ceil(): The ceil() method returns the next integer greater than or equal to a
given number.
Example:
console.log(Math.ceil(num1));
console.log(Math.ceil(num2));
console.log(Math.ceil(num3));
console.log(Math.ceil(num4));
4. Math.floor(): The floor() method returns the next integer less than or equal to a
given number.
Example:
console.log(Math.floor(num1));
console.log(Math.floor(num2));
console.log(Math.floor(num3));
console.log(Math.floor(num4));
let x = 8;
let y = 2;
console.log(Math.pow(x, y));
let x = 64;
console.log(Math.sqrt(x));
7. Math.max(): The Math.max() can be used to find the highest value in a list of
arguments:
Example:
console.log(Math.max(3, 9, 1, 5, 6));
8. Math.min(): The Math.min() can be used to find the lowest value in a list of
arguments.
Example:
console.log(Math.min(3, 9, 1, 5, 6));
console.log(Math.random());
CHAPTER 13
Window Object
What is Window Object.
In JavaScript, the window object represents the global window or the browser window in
which the JavaScript code is running. It is a top-level object and acts as the global scope
for all JavaScript code running in the browser.
The window object provides several properties and methods that allow interaction with
the browser window. Some of the commonly used properties and methods of the window
object include:
alert("Hello world")
console.log(window.location.href);
//http://127.0.0.1:5500/javascriptProject/index.html?
name=janet
console.log(window.location.pathname);///
javascriptProject/index.html?name=janet
console.log(window.location.search);//?name=janet
setTimeout(function () {
alert("Welcome to Javatpoint after 2 seconds");
}, 2000);
function startCounter() {
intervalId = setInterval(() => {
count++;
console.log("Count:", count);
}, 1000);
}
function stopCounter() {
clearInterval(intervalId);
console.log("Counter stopped");
}
window.open("joke.html");
CHAPTER 14
Introduction to Document Object Model (DOM)
What is the DOM?
DOM stands for Document Object Model. It is a programming interface that allows us to
create, change, or remove elements from the document. We can also add events to these
elements to make our page more dynamic.
The DOM views an HTML document as a tree of nodes. A node represents an HTML
element.
Let's take a look at this HTML code to better understand the DOM tree structure.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<h1>DOM tree structure</h1>
<h2>Learn about the DOM</h2>
</body>
</html>
Our document is called the root node and contains one child node which is
the <html> element. The <html> element contains two children which are
the <head> and <body> elements.
Both the <head> and <body> elements have children of their own.
Here is another way to visualize this tree of nodes.
We can access these elements in the document and make changes to them using
JavaScript.
Let's take a look at how we can work with the DOM using JavaScript.
1. getElementById()
2. getElementsByTagName()
3. getElementsByClassName()
4. querySelector()
5. querySelectorAll()
getElementById(): The getElementById() is a JavaScript function that lets you grab an
HTML element, by its id, and perform an action on it. The name of the id is passed as a
parameter, and the corresponding element is the return value.
Syntax:
Example:
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<p>Samsumg</p>
<p>Gionee</p>
<p>Nokia</p>
<p>Techno</p>
</body>
</html>
getElementsByClassName(): This method will return every element that has a class
name that is supplied as an argument. gwtElementsByClassName() returns a HTML
collection or a node-list. A node-list is an array-like object. It only works for the index
and length property but not for array methods. You can access individual item in a node-
list. With the advent of ES6, you can use the for of () to loop through.
Syntax:
const element = document.getElementsByClassName("home");
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<h1 class="home">Book one</h1>
<h1 class="home">Book two</h1>
<h1 class="home">Book three</h1>
</body>
</html>
querySelector(): The querySelector() method returns the first element that matches a
CSS selector. To return all matches (not only the first), use
the querySelectorAll() instead.
It uses the pound (#) symbol to reference an id while it uses the dot (.) symbol to
reference a class.
Syntax:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<h1 id="home">Hello world</h1>
<h1 id="home">Welcome home</h1>
<h4 class="myName">My name is John Doe</h4>
<script src="hello.js"></script>
</body>
</html>
// This will display only the first element with the home id
const home = document.querySelector("#home");
console.log(home);
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<p class="phone">Samsumg</p>
<p class="phone">Gionee</p>
<p class="phone">Nokia</p>
<p class="phone">Techno</p>
<script src="hello.js"></script>
</body>
</html>
childNodes returns all direct child nodes (not just child elements). If you are only
interested in child elements, say list items only, use the children property.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<ul id="result">
<li>Apple</li>
<li>Orange</li>
<li>Banana</li>
<li>Pawpaw</li>
<li>Mango</li>
</ul>
<script src="hello.js"></script>
</body>
</html>
The children property selects all child elements that are directly under a given element.
Here's an example of the children property in action:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<ul id="result">
<li>Apple</li>
<li>Orange</li>
<li>Banana</li>
<li>Pawpaw</li>
<li>Mango</li>
</ul>
<script src="hello.js"></script>
</body>
</html>
const result = document.querySelector("#result");
const children = result.children;
console.log(children);
parentElement or parentNode
Both parentElement or parentNode properties let you select the selected element's
parent node one level up. The critical difference is that parentElement only chooses the
parent node that is an element. On the other hand, parentNode can select a parent
regardless of whether it's an element or a different node type.
Example:
nextElementSibling or previousElementSibling
// nextSibling
const first = document.querySelector(".first");
const second = first.nextSibling;
console.log(second);
// nextSibling
const first = document.querySelector(".first");
const second = first.nextSibling.nextSibling;
console.log(second);
Example of previousSibling
// previousSibling
const last = document.querySelector(".last");
const second = last.previousSibling;
console.log(second);
// previousSibling
const last = document.querySelector(".last");
const second = last.previousSibling.previousSibling;
console.log(second);
element.style.backgroundColor = "red";
//set the background color of an element to red
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<p id="intro">This is a paragraph.</p>
<p>This is another paragraph.</p>
<script src="hello.js"></script>
</body>
</html>
// Selecting element
let elem = document.getElementById("intro");
// Appling styles on element
elem.style.color = "blue";
elem.style.fontSize = "18px";
elem.style.fontWeight = "bold";
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<div id="result">
<h1>Hello world</h1>
<div class="second">
<h2>Second heading</h2>
</div>
</div>
<script src="hello.js"></script>
</body>
</html>
Therefore, in JavaScript, the CSS property names that contain one or more hyphens are
converted to intercapitalized style word. It is done by removing the hyphens and
capitalizing the letter immediately following each hyphen, thus the CSS property font-
size becomes the DOM property fontSize, border-left-style becomes borderLeftStyle,
and so on.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<p id="intro">This is a paragraph.</p>
<p>This is another paragraph.</p>
<script src="hello.js"></script>
</body>
</html>
// Selecting element
let elem = document.getElementById("intro");
// Appling styles on element
elem.style.backgroundColor = "yellow";
elem.style.fontSize = "18px";
elem.style.fontWeight = "bold";
CHAPTER 17
DOM Manipulation
DOM manipulation is the interaction of the JavaScript DOM API to modify or change the
HTML document. With DOM manipulation, you can create, modify, style, or delete
elements without a refresh. It also promotes user interactivity with browsers.
Adding CSS Classes to Elements
You can also get or set CSS classes to the HTML elements using the className property.
Since, class is a reserved word in JavaScript, so JavaScript uses the className property
to refer the value of the HTML class attribute.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<p id="intro">This is a paragraph.</p>
<script src="hello.js"></script>
</body>
</html>
// Selecting element
Example
let elem = document.getElementById("intro");
elem.className = "note";
let myNote = document.querySelector(".note");
// Appling styles on element
myNote.style.backgroundColor = "pink";
myNote.style.fontSize = "48px";
myNote.style.fontWeight = "bold";
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<p id="intro">This is a paragraph.</p>
<p class="good">Good girl gone bad</p>
<p class="bad">Bad girl gone good</p>
<script src="hello.js"></script>
</body>
</html>
const good = document.querySelector(".good");
const way = (good.className = "text");
console.log(good);
There is even better way to work with CSS classes. You can use the classList property to
get, set or remove CSS classes easily from an element.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<div id="info" class="disabled">Something very important!
</div>
<script src="hello.js"></script>
</body>
</html>
// Selecting element
let elem = document.getElementById("info");
elem.classList.add("hide"); // Add a new class
elem.classList.add("note", "highlight"); // Add multiple classes
elem.classList.remove("hide"); // Remove a class
elem.classList.remove("disabled", "note"); // Remove multiple
classes
elem.classList.toggle("visible"); // If class exists remove it,
if not add it
console.log(elem);
contains
The contains() method is used to determines whether the collection contains a given item
or not.
Creating Elements
in JavaScript You use the createElement () to create element
Creating TextNode
The createTextNode() method creates a text node.
Example:
To add an id element
AppendChild
AppendChild() – To append a child to a parent element
Remove
Remove elements from DOM – remove()
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<style>
.myColor {
color: blue;
}
</style>
<body>
<div id="info" class="disabled">Something very important!
</div>
<div>
<h1>Nigeria</h1>
<h2>Ghana</h2>
<h3>Togo</h3>
</div>
<script src="hello.js"></script>
</body>
</html>
removeChild
removeChild():
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<style>
.myColor {
color: blue;
}
</style>
<body>
<div id="info" class="disabled">Something very important!
</div>
<div id="result">
<h1>Nigeria</h1>
<h2>Ghana</h2>
<h3>Togo</h3>
</div>
<script src="hello.js"></script>
</body>
</html>
setAttribute
setAttribute() – To set attribute to elements in DOM
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<style>
.myColor {
color: blue;
}
</style>
<body>
<div id="info" class="disabled">Something very important!
</div>
<h3 class="good">Home</h3>
<script src="hello.js"></script>
</body>
</html>
removeAttribute
removeAttribute() – To remove attribute from elements in DOM
2. innerHTML property returns the string inside our div and the HTML (or XML)
markup contained within our string, including any spacing, line breaks and
formatting irregularities.
Example:
3. textContent property returns the raw content with styling inside of all elements,
but excludes the HTML element tags.
Example:
const displayText = document.createElement("div");
displayText.textContent = "<b>I love programming<b>";
displayText.style.color = "red";
document.body.appendChild(displayText);
CHAPTER 18
Events
What is an Event?
JavaScript's interaction with HTML is handled through events that occur when the user or
the browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is
an event. Other examples include events like pressing any key, closing a window,
resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which cause
buttons to close windows, messages to be displayed to users, data to be validated, and
virtually any other type of response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML
element contains a set of events which can trigger JavaScript Code.
Here are some of the few events:
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<button type="button" onclick="sayHello()">Say
Hello</button>
</form>
<script src="hello.js"></script>
</body>
</html>
function sayHello() {
alert("Hello World");
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<p>Bring your mouse inside the division to see the
result:</p>
<img src="images/backgroung.png "
width="250px" height="250px" onmouseover="over()"
alt="">
<div onmouseout="out()">
<h2> This is inside the division </h2>
</div>
<script src="hello.js"></script>
</body>
</html>
function over() {
document.write("Mouse Over");
}
function out() {
document.write("Mouse Out");
}
There are other events which you can explore on but we will not cover it in this manual.
Event Listeners
An event listener is a function that initiates a predefined process if a specific event
occurs. So, an event listener “listens” for an action, then calls a function that performs a
related task. This event can take one of many forms. Common examples include mouse
events, keyboard events, and window events.
Many web applications rely on some form of event to carry out their functions. At some
point, a human interacts with their interface, which generates an event. These human-
driven events typically rely on a peripheral device, such as a mouse or keyboard.
When a device creates an event, the program can listen for it, to know when to carry out
specific behavior. In this tutorial, you’ll learn how to listen for events using JavaScript.
element.addEventListener("event", functionToExecute);
Where:
the element can represent any HTML tag (from a button to a paragraph)
the “event” is a string naming a specific, recognized action
the functionToExecute is a reference to an existing function
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<h1 class="hello">Hello world!</h1>
<button id="addClick">Click me</button>
<script src="hello.js"></script>
</body>
</html>
This will trigger an action “You have just clicked me” once the button is clicked
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<style>
.reveal {
color: white;
background-color: red;
padding: 5px;
}
</style>
<body>
<div>
<h1 class="msg">Welcome to JavaScript training</h1>
<button type="button" id="btn">Toggle Message</button>
</div>
<script src="hello.js"></script>
</body>
</html>
btn.addEventListener("click", function () {
if (msg.classList.contains("msg")) {
msg.classList.remove("msg");
msg.classList.add("reveal");
console.log(msg);
} else {
console.log("NO");
}
});
You can as well replace the function() with a variable name and declare it somewhere
else in your code.
Example:
btn.addEventListener("click", changeMe);
// Create a function
function changeMe() {
if (msg.classList.contains("msg")) {
msg.classList.toggle("reveal");
} else {
console.log("NO");
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<h1>Form event</h1>
<form action="" method="post" id="myForm">
<label for="Username">Username</label>
<input type="text" name="username" id="username"
placeholder="Enter
username"> <br><br>
<label for="Password">Password</label>
<input type="password" name="password" id="password"
placeholder="Enter
password"><br><br>
<button type="submit" id="btn">Submit</button>
</form>
</div>
<script src="hello.js"></script>
</body>
</html>
If you noticed, on the console the message blinks and did not display result permanently,
this is as a result of the browser that automatically reloads a page whenever a form is
submitted. To prevent this action you will need to insert the “e.preventDefault()” method
to stop the browser from reloading your form.
e.preventDefault() stops the browser from reloading after a form is submitted. Inshort
e.preventDefault() prevents default behavior.
// Form events
const myForm = document.getElementById("myForm");
const username = document.getElementById("username");
const password = document.getElementById("password");
myForm.addEventListener("submit", formEvent);
function formEvent(e) {
e.preventDefault();
console.log("Form submitted");
}
To get what the user’s typed in the form, you use the .value property.
Example
// Form events
const myForm = document.getElementById("myForm");
const username = document.getElementById("username");
const password = document.getElementById("password");
myForm.addEventListener("submit", formEvent);
function formEvent(e) {
e.preventDefault();
console.log(username.value);
console.log(password.value);
console.log("Form submitted");
}
Example:
Let create a To-do app
Index.html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?
family=DM+Sans:wght@400;500;700&display=swap"
rel="stylesheet"
/>
<title>Document</title>
<style>
body {
font-family: "DM Sans", sans-serif;
background-color: rgb(9, 43, 75);
height: 90vh;
box-sizing: border-box;
}
.todo-text {
text-align: center;
}
.todo-text h2 {
color: white;
}
#form {
display: flex;
justify-content: center;
margin: 60px 0px;
}
#todo {
padding: 10px;
margin: 0px 20px;
/* border-radius: 10px; */
/* border: none; */
/* box-shadow: none; */
width: 280px;
/* height: 90px; */
}
#form button {
border-radius: 10px;
border: none;
padding: 0 25px;
background-color: #27649c;
color: white;
font-size: 18px;
}
.todoText {
list-style-type: none;
display: flex;
flex-direction: column;
align-items: center;
}
.todoText li {
background-color: #f8f9fa;
border-radius: 10px;
box-shadow: 1px 1px 10px black;
width: 300px;
/* height: 45px; */
padding: 20px;
margin: 10px 0px;
}
.todo-app {
padding: 10px 10px;
}
</style>
</head>
<body>
<div class="todo-app">
<div class="todo-text">
<h2>TODO APP</h2>
<img src="images.jpg" width="90" />
</div>
<form id="form">
<input type="text" id="todo" />
<button class="todo_submit">Submit</button>
</form>
<div>
<h2 style="text-align: center; color: white">Todo List</h2>
<div class="todo-item">
<ul class="todoText">
<!-- <li>Rice</li> -->
</ul>
</div>
</div>
</div>
<script src="Todo.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
</body>
</html>
myForm.addEventListener("submit", todoApp);
Note: what we want to achieve is that anytime we click on submit button it should add a
new list to the parent list, that is the reason why we used appendChild
myForm.addEventListener("submit", todoApp);
let output;
function todoApp(e) {
e.preventDefault();
// creating li element
const li = document.createElement("li");
// console.log(todoText);
if (todoInput.value.length == "0") {
swal("Please enter a text", "", "error");
} else {
output = todoInput.value;
li.append(output);
todoText.appendChild(li);
}
}
// console.log(li);
Form Validation
Form validation normally used to occur at the server, after the client had entered all the
necessary data and then pressed the submit button. If the data entered by the client
was incorrect or was simply missing, the server would have to send all the data back to
the client and request that the form be resubmitted with the correct information.
JavaScript provides a way to validate the form’s data on the client’s computer before
sending it to the web server.
Example of form validation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<h1>Form event</h1>
<form action="" method="post" id="myForm">
<h6 class="output"></h6>
<label for="Username">FirstName</label>
<input type="text" name="firstname" id="firstname"
placeholder="Enter
firstname"> <br><br>
<label for="Username">LastName</label>
<input type="text" name="lastname" id="lastname"
placeholder="Enter
lastname"> <br><br>
<label for="Username">Email</label>
<input type="text" name="email" id="email"
placeholder="Enter email">
<br><br>
<label for="Username">Phone</label>
<input type="text" name="phone" id="phone"
placeholder="Enter phone">
<br><br>
<label for="Password">Password</label>
<input type="password" name="password" id="password"
placeholder="Enter
password"><br><br>
<button type="submit" id="btn">Submit</button>
</form>
</div>
<script src="hello.js"></script>
</body>
</html>
SetItem()
SetItem() is used to save data to local storage.
Example:
To see the item in your local storage, you right click the browser, click on “inspect” then
click on “Application” on the console, then click on “Local Storage” to view the stored
item.
Note: If the data to be stored is an array or object it has to be converted to a string by
using the JSON.stringify()
// Convert an array to a string before saving into localStorage
const students = ["John", "Mary", "Michael"];
localStorage.setItem("myStudents", JSON.stringify(students));
GetItem()
GetItem() is used to get item from local storage. getItem() accepts only one parameter,
which is the key, and returns the value as a string.
To do this, we make use of the JSON.parse() method, which converts a JSON string into
a JavaScript object.
JSON.parse(window.localStorage.getItem('person'));
RemoveItem()
Remove an item by key from local storage.
When passed a key name, the removeItem() method removes that key from the storage if
it exists. If there is no item associated with the given key, this method will do nothing.
Clear()
Clear all items in local storage.
console.log(user.dataset.id); //1234567890
console.log(user.dataset.user); //carinaanand
// if the name is more than one word you will camselcase rule
console.log(user.dataset.dateOfBirth); //""
user.dataset.dateOfBirth = 22;
console.log(user.dataset.dateOfBirth); //22
<ul>
<li class="filterable-item" data-filter="fruit">Apple</li>
<li class="filterable-item" data-filter="fruit">Banana</li>
<li class="filterable-item" data-filter="vegetable">Carrot</li>
<li class="filterable-item" data-filter="vegetable">Potato</li>
</ul>
filterButtons.forEach((button) => {
button.addEventListener("click", () => {
const filterValue = button.dataset.filter;
filterableItems.forEach((item) => {
if (item.dataset.filter === filterValue || filterValue === "all") {
item.classList.remove("hidden");
} else {
item.classList.add("hidden");
}
});
});
});
CHAPTER 21
Asynchronous JavaScript
The word asynchronous means not occurring at the same time. What does it mean in
the context of JavaScript?
Typically, executing things in sequence works well. But you may sometimes need to
fetch data from the server or execute a function with a delay, something you do not
anticipate occurring NOW. So, you want the code to execute asynchronously.
Asynchronous governs how we perform tasks which take some time to complete.
Asynchronous start something and finish later. In order word asynchronous don’t need
to finish a task before executing another task.
HTTP Request
We make HTTP request to get data from another server. For example, when you type a
web address you are performing a request. E.g., when you type
https://www.facebook.com you are searching for that is responsible for such data. Then
the server sends the HTTP response message.
We make this request to API end point. The API send back data in JSON format.
JSON
JSON stands for JavaScript Object Notation. JSON is a string that looks like JavaScript
object. JSON is the format we get back once we send a HTTP request to a remote server.
Example of JSON
{"employees":[
{"name":"Shyam", "email":"shyamjaiswal@gmail.com"},
{"name":"Bob", "email":"bob32@gmail.com"},
{"name":"Jai", "email":"jai87@gmail.com"}
]}
{
"employee": {
"name": "sonoo",
"salary": 56000,
"married": true
}
}
API
API stands for Application Programming Interface. An API is simply a medium to fetch or
send data between interfaces. Let’s say you want to make an application that provides
the user with some real-time data fetched from the server or maybe even allows you to
modify or add data to some other endpoint. This is made possible by the API or the
Application Programming Interface.
We will use a simple public API that requires no authentication and allows you to fetch
some data by querying the API with GET requests. https://randomuser.me/ is a website
that provides dummy data for random users that we can easily work with. We can get
the response by making a request to https://randomuser.me/api/. The JSON response
that we receive in the following format.
{
"results": [
{
"gender": "female",
"name": {
"title": "Miss",
"first": "Nina",
"last": "Simmmons"
},
"location": {
"street": {
"number": 970,
"name": "Eason Rd"
},
"city": "Fullerton",
"state": "Wyoming",
"country": "United States",
"postcode": 57089,
"coordinates": {
"latitude": "83.1807",
"longitude": "104.7170"
},
"timezone": {
"offset": "+8:00",
"description":
"Beijing, Perth, Singapore, Hong Kong"
}
},
"email": "nina.simmmons@example.com",
"login": {
"uuid": "bd0d135f-84df-4102-aa4f-5baaa41baf5c",
"username": "yellowfrog722",
"password": "dawg",
"salt": "q28gdiyN",
"md5": "291987daea22bb91775226574925b271",
"sha1": "a0463a26ea5c2ff4f3ad498fd01c5994926e5021",
"sha256":
"6583eb74ca08bfac50b3b29aa52c9f02ea5d9d017fef0e5a5a6fae4f5225f928
"
},
"dob": {
"date": "1980-11-01T23:10:05.403Z",
"age": 40
},
"registered": {
"date": "2013-04-02T02:26:52.904Z",
"age": 7
},
"phone": "(216)-693-7015",
"cell": "(501)-534-9413",
"id": {
"name": "SSN",
"value": "847-09-2973"
},
"picture": {
"large":
"https://randomuser.me/api/portraits/women/60.jpg",
"medium":
"https://randomuser.me/api/portraits/med/women/60.jpg",
"thumbnail":
"https://randomuser.me/api/portraits/thumb/women/60.jpg"
},
"nat": "US"
}
],
"info": {
"seed": "82a8d8d4a996ba17",
"results": 1,
"page": 1,
"version": "1.3"
}