Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
78 views

JavaScript Docs

Uploaded by

umarfarooque869
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views

JavaScript Docs

Uploaded by

umarfarooque869
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

JavaScript

• JavaScript is the world's most popular programming language.


• JavaScript is the programming language of the Web.
• JavaScript is easy to learn.
• JavaScript and Java are completely different languages, both in concept and design.
• JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in
1997.
• ECMA-262 is the official name of the standard. ECMAScript is the official name of the
language.

Example Program
<!DOCTYPE html>
<html>
<body>
<h2>My First JavaScript</h2>
<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>
<p id="demo"></p>
</body>
</html>

Why Study JavaScript?


JavaScript is one of the 3 languages all web developers must learn:
1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web pages
Commonly Asked Questions
• How do I get JavaScript? - You don't have to get or download JavaScript.
• Where can I download JavaScript? - JavaScript is already running in your browser on
your computer, on your tablet, and on your smart-phone.
• Is JavaScript Free? - JavaScript is free to use for everyone.

What JavaScript can do?


• JavaScript Can Change HTML Content
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello
JavaScript!"'>Click Me!</button>
</body>
</html>

• JavaScript Can Change HTML Attribute Values


<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can change HTML attribute values.</p>
<p>In this case JavaScript changes the value of the src (source) attribute of an image.</p>
<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the
light</button>
<img id="myImage" src="pic_bulboff.gif" style="width:100px">
<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the
light</button>
</body>
</html> Output

• JavaScript Can Change HTML Styles (CSS)


<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click
Me!</button>
</body>
</html>

• JavaScript Can Hide HTML Elements


<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can hide HTML elements.</p>
<button type="button" onclick="document.getElementById('demo').style.display='none'">Click
Me!</button>
</body>
</html>
• JavaScript Can Show HTML Elements
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can show hidden HTML elements.</p>
<p id="demo" style="display:none">Hello JavaScript!</p>
<button type="button" onclick="document.getElementById('demo').style.display='block'">Click
Me!</button>
</body>
</html>

JavaScript Display Possibilities


• Writing into an HTML element, using innerHTML.
<!DOCTYPE html>
<html>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Changing the innerHTML property of an HTML element is a common way to display data
in HTML.

• Writing into the HTML output using document.write().


<!DOCTYPE html>
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<p>Never call document.write after the document has finished loading.
It will overwrite the whole document.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Using document.write() after an HTML document is loaded, will delete all existing HTML
<!DOCTYPE html>
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<button type="button" onclick="document.write(5 + 6)">Try it</button>
</body>
</html>

• Writing into an alert box, using window.alert().


<!DOCTYPE html>
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
You can skip the window keyword.

• Writing into the browser console, using console.log().


<!DOCTYPE html>
<html>
<body>
<h2>Activate Debugging</h2>
<p>F12 on your keyboard will activate debugging.</p>
<p>Then select "Console" in the debugger menu.</p>
<p>Then click Run again.</p>
<script>
console.log(5 + 6);
</script>
</body>
</html>

JavaScript Print
JavaScript does not have any print object or print methods.
You cannot access output devices from JavaScript.
The only exception is that you can call the window.print() method in the browser to print the
content of the current window.
<!DOCTYPE html>
<html>
<body>
<h2>The window.print() Method</h2>
<p>Click the button to print the current page.</p>
<button onclick="window.print()">Print this page</button>
</body>
</html>

JavaScript Syntax
JavaScript syntax is the set of rules, how JavaScript programs are constructed.
The JavaScript syntax defines two types of values:
• Fixed values
• Variable values
Fixed values are called Literals.
Variable values are called Variables.

The two most important syntax rules for fixed values are:
1. Numbers are written with or without decimals.
2. Strings are text, written within double or single quotes.

JavaScript Comments
• JavaScript comments can be used to explain JavaScript code, and to make it more
readable.
• JavaScript comments can also be used to prevent execution, when testing alternative
code.
Single Line Comments

• Single line comments start with //.


• Any text between // and the end of the line will be ignored by JavaScript (will not be
executed).
Multi-line Comments

• Multi-line comments start with /* and end with */.


• Any text between /* and */ will be ignored by JavaScript.

JavaScript Variables
Variables are Containers for Storing Data
JavaScript Variables can be declared in 4 ways:
• Automatically
x = 5;
y = 6;
z = x + y;

• Using var
var x = 5;
var y = 6;
var z = x + y;

• Using let
let x = 5;
let y = 6;
let z = x + y;

• Using const
const x = 5;
const y = 6;
const z = x + y;

When to Use var, let, or const?


1. Always declare variables
2. Always use const if the value should not be changed
3. Always use const if the type should not be changed (Arrays and Objects)
4. Only use let if you can't use const
5. Only use var if you MUST support old browsers.

JavaScript Identifiers
All JavaScript variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
• Names can contain letters, digits, underscores, and dollar signs.
• Names must begin with a letter.
• Names can also begin with $ and _ (but we will not use it in this tutorial).
• Names are case sensitive (y and Y are different variables).
• Reserved words (like JavaScript keywords) cannot be used as names.

JavaScript Let
• The let keyword was introduced in ES6 (2015)
• Variables declared with let have Block Scope
• Variables declared with let must be Declared before use
• Variables declared with let cannot be Redeclared in the same scope
Explanation

JavaScript Const
• The const keyword was introduced in ES6 (2015)
• Variables defined with const cannot be Redeclared
• Variables defined with const cannot be Reassigned
• Variables defined with const have Block Scope
Explanation

JavaScript Operators
There are different types of JavaScript operators:
• Arithmetic Operators
• Assignment Operators
• Comparison Operators
• String Operators
• Logical Operators
• Bitwise Operators
• Ternary Operators
• Type Operators
Explanation

JavaScript Data Types


Primitive Data Types
A primitive type is predefined by the language and is named by a reserved keyword.
1. String
2. Number
3. Bigint
4. Boolean
5. Undefined
6. Null
7. Symbol
8. Object

The Object Data Type / Non-Primitive Data Types


Non-primitive types are created by the programmer and is not defined by the language. Non-
primitive types can be used to call methods to perform certain operations, while primitive types
cannot. A primitive type has always a value, while non-primitive types can be null.
The object data type can contain:
1. An object
2. An array
3. A date
4. A function
Explanation

JavaScript Functions
• A JavaScript function is a block of code designed to perform a particular task.
• A JavaScript function is executed when "something" invokes it (calls it).

Why Functions?

• With functions you can reuse code.


• You can write code that can be used many times.
• You can use the same code with different arguments, to produce different results.

JavaScript Function Syntax

• A JavaScript function is defined with the function keyword, followed by a name,


followed by parentheses ().
• Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).
• The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
• The code to be executed, by the function, is placed inside curly brackets: {}
Example
function name(parameter1, parameter2, parameter3) {
// code to be executed
}

• 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.

Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:
• When an event occurs (when a user clicks a button)
• When it is invoked (called) from JavaScript code
• Automatically (self invoked)

Example
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<p>Call a function which performs a calculation and returns the result:</p>
<p id="demo"></p>
<script>
function myFunction(p1, p2) {
return p1 * p2;
}
let result = myFunction(4, 3);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
Function Return

• When JavaScript reaches a return statement, the function will stop executing.
• If the function was invoked from a statement, JavaScript will "return" to execute the
code after the invoking statement.
• Functions often compute a return value. The return value is "returned" back to the
"caller"
Example
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<p>Call a function which performs a calculation and returns the result:</p>
<p id="demo"></p>
<script>
let x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
}
</script>
</body>
</html>

Ways to Write Functions in JavaScript


Function Declaration
Function Declaration is the traditional way to define a function. It is somehow similar to the
way we define a function in other programming languages. We start declaring using the
keyword “function”. Then we write the function name and the parameters.
function add(a,b) {
console.log(a+b);
}
add(2,3);

Function Expression
Function Expression is another way to define a function in JavaScript. Here we define a function
using a variable and store the returned value in that variable.
const res = function (a,b) {
console.log(a+b);
}
res(2,7);

Arrow Functions
Arrow functions are been introduced in the ES6 version of JavaScript. It is used to shorten the
code. Here we do not use the “function” keyword and use the arrow symbol.
const sum = (a,b) => a+b;
sum(4,6);
// Multiple line of code
const great = (a, b) => {
if (a > b)
return "a is greater";
else
return "b is greater";
}
great(3, 5);
JavaScript Objects
Real Life Objects, Properties, and Methods

• In real life, a car is an object.


• A car has properties like weight and color, and methods like start and stop:
• All cars have the same properties, but the property values differ from car to car.
• All cars have the same methods, but the methods are performed at different times.
• The values are written as name:value pairs (name and value separated by a colon).
• It is a common practice to declare objects with the const keyword.

Object Definition
You define (and create) a JavaScript object with an object literal.
Spaces and line breaks are not important. An object definition can span multiple lines.
const person = {firstName:"abc", lastName:"xyz", age:25, eyeColor:"green"};
OR
const person = {
firstName: "abc",
lastName: "xyz",
age: 25,
eyeColor: "green"
};

Object Properties
The name:values pairs in JavaScript objects are called properties.

Accessing Object Properties


You can access object properties in two ways:
objectName.propertyName - person.lastName;
OR
objectName["propertyName"] - person["lastName"];

Object Methods

• Objects can also have methods.


• Methods are actions that can be performed on objects.
• Methods are stored in properties as function definitions.
Example
const person = {
firstName: "Hello",
lastName : "World",
id : 101,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

What is this?

• In JavaScript, the this keyword refers to an object.


• Which object depends on how this is being invoked (used or called).
• The this keyword refers to different objects depending on how it is used
• In an object method, this refers to the object.
• Alone, this refers to the global object.
• In a function, this refers to the global object.
• In a function, in strict mode, this is undefined.
• In an event, this refers to the element that received the event.
• Methods like call(), apply(), and bind() can refer this to any object.
• Note - this is not a variable. It is a keyword. You cannot change the value of this.

Accessing Object Methods


objectName.methodName() - name = person.fullName();
If you access a method without the () parentheses, it will return the function definition.

JavaScript Events
An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:
• An HTML web page has finished loading
• An HTML input field was changed
• An HTML button was clicked
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
With single quotes: <element event='some JavaScript'>
With double quotes: <element event="some JavaScript">

Types of Events

• Window Events
• Keyboard Events
• Mouse Events
• Drag & Drop Events
• Form Events
Example – onchange, onclick, onmouseover, onkeydown, onkeyup, onload, etc.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onclick Attribute</h2>
<p>Click the button to display the date.</p>
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>
</body>
</html>

JavaScript Strings
Strings are for storing text. Strings are written with quotes.
let Name1 = "Hello World"; // Double quotes
let Name2 = 'Hello World'; // Single quotes
Note : Strings created with single or double quotes works the same. There is no difference
between the two.
Quotes Inside Quotes : You can use quotes inside a string, as long as they don't match the
quotes surrounding the string.
let line1 = "It's alright";
let line2 = "It is called 'JavaScript'";
let line3 = 'It is called "JavaScript"';

String Methods
String Length - The length property returns the length of a string.
let text = "It is called JavaScript";
let length = text.length;

Extracting String Parts


There are 3 methods for extracting a part of a string:
• slice(start, end)
• substring(start, end)
• substr(start, length)

slice()
slice() 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).
<p id="demo"></p>
<script>
let text = "Apple, Banana, Kiwi";
let part = text.slice(7,13);
document.getElementById("demo").innerHTML = part;
</script>

If you omit the second parameter, the method will slice out the rest of the string:
let text = "Apple, Banana, Kiwi";
let part = text.slice(7);
If a parameter is negative, the position is counted from the end of the string:
let text = "Apple, Banana, Kiwi";
let part = text.slice(-12);
This example slices out a portion of a string from position -12 to position -6:
let text = "Apple, Banana, Kiwi";
let part = text.slice(-12, -6);

substring()
substring() is similar to slice(). The difference is that start and end values less than 0 are treated
as 0 in substring().
<p id="demo"></p>
<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.substring(7,13);
</script>
If you omit the second parameter, substring() will slice out the rest of the string.

substr()
substr() is similar to slice(). The difference is that the second parameter specifies the length of
the extracted part.
<p id="demo"></p>
<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.substr(7,6);
</script>
If you omit the second parameter, substr() will slice out the rest of the string.
If the first parameter is negative, the position counts from the end of the string.

Converting to Upper and Lower Case


A string is converted to upper case with toUpperCase():
let text1 = "Hello World!";
let text2 = text1.toUpperCase();
A string is converted to lower case with toLowerCase():
let text1 = "Hello World!";
let text2 = text1.toLowerCase();

concat()
concat() joins two or more strings:
<p id="demo"></p>
<script>
let text1 = "Hello";
let text2 = "World!";
let text3 = text1.concat(" ",text2);
document.getElementById("demo").innerHTML = text3;
</script>
The concat() method can be used instead of the plus operator. These two lines do the same:
text = "Hello" + " " + "World!";
text = "Hello".concat(" ", "World!");
Note : All string methods return a new string. They don't modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only replaced.

repeat()

• It returns a string with a number of copies of a string.


• It returns a new string.
• It does not change the original string.
Syntax - string.repeat(count)
<p id="demo"></p>
<script>
let text = "Hello world!";
let result = text.repeat(2);
document.getElementById("demo").innerHTML = result;
</script>

replace()

• It does not change the string it is called on.


• It returns a new string.
• It replaces only the first match
<button onclick="replace()">Try it</button>
<p id="demo"> Hello World in Python</p>
<script>
function replace() {
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML =
text.replace ("Python","JavaScript");
}
</script>

To replace all matches, use a regular expression with a /g flag (global match).
let text = "Hello World in Python, Hello World in JavaScript";
let newText = text.replace(/Hello/g, "Namaste");
To replace case insensitive, use a regular expression with an /i flag (insensitive).
let text = "Hello World";
let newText = text.replace(/HELLO/i, "Namste");

replaceAll()
<p>ES2021 intoduced the string method replaceAll().</p>
<p id="demo"></p>
<script>
let text = "I love cats. Cats are very easy to love. Cats are very popular."
text = text.replaceAll("Cats","Dogs");
text = text.replaceAll("cats","dogs");
document.getElementById("demo").innerHTML = text;
</script>

String Search Methods


• indexOf()
• lastIndexOf()
• search()
• match()
• matchAll()
• includes()
• startsWith()
• endsWith()

Template Strings
• Templates were introduced with ES6 (JavaScript 2016).
• Templates are strings enclosed in backticks (`This is a template string`).
• Templates allow single and double quotes inside a string.
• Also known as String Templates, Template Strings, Template Literals, etc.
Example : let text = `It is called "JavaScript"`;

String Interpolation
Template String provide an easy way to interpolate variables and expressions into strings. The
method is called string interpolation.
Syntax : ${……………}

Variable Substitutions
Template Strings allow variables in strings:
<p id="demo"></p>
<script>
let firstName = "abc";
let lastName = "xyz";
let text = `Welcome ${firstName}, ${lastName}!`;
document.getElementById("demo").innerHTML = text;
</script>
Automatic replacing of variables with real values is called string interpolation.
Expression Substitution
Template Strings allow expressions in strings:
<p id="demo"></p>
<script>
let price = 10;
let VAT = 0.25;
let total = `Total: ${(price * (1 + VAT)).toFixed(2)}`;
document.getElementById("demo").innerHTML = total;
</script>

Example
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Template Strings</h1>
<p>Templates allow variables in strings:</p>
<p id="demo"></p>
<p>Templates are not supported in Internet Explorer.</p>
<script>
let header = "Template Strings";
let tags = ["template strings", "javascript", "es6"];
let html = `<h2>${header}</h2><ul>`;
for (const x of tags) {
html += `<li>${x}</li>`;
}
html += `</ul>`;
document.getElementById("demo").innerHTML = html;
</script>
</body>
</html>

Arrays
• An array is a special variable, which can hold more than one value.
• An array can hold many values under a single name, and you can access the values by
referring to an index number.
Syntax:
const array_name = [item1, item2, ...]; - const cars = ["Audi", "Volvo", "BMW"];
let car = cars[0];
Note: Array indexes start with 0. [0] is the first element. [1] is the second element.

Changing an Array Element


This statement changes the value of the first element in cars:
const cars = ["Audi", "Volvo", "BMW"];
cars[0] = "Merc";

Access the Full Array


With JavaScript, the full array can be accessed by referring to the array name:
const cars = ["Audi", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;

The Difference between Arrays and Objects

• In JavaScript, arrays use numbered indexes.


• In JavaScript, objects use named indexes.
• Arrays are a special kind of objects, with numbered indexes.

When to Use Arrays. When to use Objects.


• JavaScript does not support associative arrays.
• You should use objects when you want the element names to be strings (text).
• You should use arrays when you want the element names to be numbers.

Array Methods

• length • concat() • toReversed()


• toString() • copyWithin() • Numeric Sort
• at() • flat() • Random Sort
• join() • splice() • Math.min()
• pop() • toSpliced() • Math.max()
• push() • slice() • Array forEach
• shift() • sort() • Array map()
• unshift() • reverse() • Array filter()
• delete() • toSorted() • Array reduce()

Array Const

• It has become a common practice to declare arrays using const.


• An array declared with const cannot be reassigned.
const cars = ["Audi", "Volvo", "BMW"];
cars = ["Toyota", "Mustang", "Merc"]; // ERROR

Arrays are Not Constants

• The keyword const is a little misleading.


• It does NOT define a constant array. It defines a constant reference to an array.
• Because of this, we can still change the elements of a constant array.

Conditional Statements
Conditional statements are used to perform different actions based on different conditions.
In JavaScript we have the following conditional statements:
• Use if to specify a block of code to be executed, if a specified condition is true
• Use else to specify a block of code to be executed, if the same condition is false
• Use else if to specify a new condition to test, if the first condition is false
• Use switch to specify many alternative blocks of code to be executed

The if Statement
Use the if statement to specify a block of JavaScript code to be executed if a condition is true.
if (condition) {
// block of code to be executed if the condition is true
}
<h2>JavaScript if</h2>
<p>Display "Good day!" if the hour is less than 18:00:</p>
<p id="demo">Good Evening!</p>
<script>
if (new Date().getHours() < 18) {
document.getElementById("demo").innerHTML = "Good day!";
}
</script>

The else Statement


Use the else statement to specify a block of code to be executed if the condition is false.
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
<h2>JavaScript if .. else</h2>
<p>A time-based greeting:</p>
<p id="demo"></p>
<script>
const hour = new Date().getHours();
let greeting;
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
document.getElementById("demo").innerHTML = greeting;
</script>

The else if Statement


Use the else if statement to specify a new condition if the first condition is false.
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
<h2>JavaScript else if</h2>
<p>A time-based greeting:</p>
<p id="demo"></p>
<script>
const time = new Date().getHours();
let greeting;
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
document.getElementById("demo").innerHTML = greeting;
</script>

Switch Statement
The switch statement is used to perform different actions based on different conditions. Use
the switch statement to select one of many code blocks to be executed.
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
<h2>JavaScript switch</h2>
<p id="demo"></p>
<script>
let day;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script>

The break Keyword

• When JavaScript reaches a break keyword, it breaks out of the switch block.
• This will stop the execution inside the switch block.
• It is not necessary to break the last case in a switch block. The block breaks (ends) there
anyway.
• Note: If you omit the break statement, the next case will be executed even if the
evaluation does not match the case.

The default Keyword


The default keyword specifies the code to run if there is no case match.

Loops
Loops are handy, if you want to run the same code over and over again, each time with a
different value.
text += cars[0] + "<br>";
text += cars[1] + "<br>";
for (let i = 0; i < cars.length; i++) {
text += cars[2] + "<br>"; OR
text += cars[i] + "<br>";
text += cars[3] + "<br>";
}
text += cars[4] + "<br>";
text += cars[5] + "<br>";

Types of Loops
JavaScript supports different kinds of loops:
• for - loops through a block of code a number of times
• for/in - loops through the properties of an object
• for/of - loops through the values of an iterable object
• while - loops through a block of code while a specified condition is true
• do/while - also loops through a block of code while a specified condition is true

For Loop
for (expression 1; expression 2; expression 3) {
// code block to be executed
}
<h2>JavaScript For Loop</h2>
<p id="demo"></p>
<script>
let text = "";
for (let i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
For In Loop
The JavaScript for in statement loops through the properties of an Object.
for (key in object) {
// code block to be executed
}
<p>The for in statement loops through the properties of an object:</p>
<p id="demo"></p>
<script>
const person = {fname:"abc", lname:"xyz", age:25};
let txt = "";
for (let x in person) {
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>

For In Over Arrays


The JavaScript for in statement can also loop over the properties of an Array.
for (variable in array) {
code
}
<p>The for in statement can loops over array values:</p>
<p id="demo"></p>
<script>
const numbers = [45, 4, 9, 16, 25];
let txt = "";
for (let x in numbers) {
txt += numbers[x] + "<br>";
}
document.getElementById("demo").innerHTML = txt;
</script>

For Of Loop
The JavaScript for of statement loops through the values of an iterable object.
It lets you loop over iterable data structures such as Arrays, Strings, Maps, NodeLists, and more.
for (variable of iterable) {
// code block to be executed
}
variable - For every iteration the value of the next property is assigned to the variable. Variable
can be declared with const, let, or var.
iterable - An object that has iterable properties.

Looping over an Array


<p id="demo"></p>
<script>
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

Looping over a String


<p id="demo"></p>
<script>
let language = "JavaScript";
let text = "";
for (let x of language) {
text += x + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

While Loop
The while loop loops through a block of code as long as a specified condition is true.
while (condition) {
// code block to be executed
}
<h2>JavaScript While Loop</h2>
<p id="demo"></p>
<script>
let text = "";
let i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>

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, and then it will repeat the loop as long as the condition
is true.
do {
// code block to be executed
}
while (condition);
<h2>JavaScript Do While Loop</h2>
<p id="demo"></p>
<script>
let text = ""
let i = 0;
do {
text += "<br>The number is " + i;
i++;
}
while (i < 10);
document.getElementById("demo").innerHTML = text;
</script>

Hoisting
• Hoisting is JavaScript's default behavior of moving declarations to the top.
• In JavaScript, a variable can be declared after it has been used.
• In other words; a variable can be used before it has been declared.
<p id="demo"></p>
<script>
x = 5;
elem = document.getElementById("demo");
elem.innerHTML = x;
var x;
</script>

Initializations are Not Hoisted


JavaScript only hoists declarations, not initializations.
<p id="demo"></p>
<script>
var x = 5;
elem = document.getElementById("demo");
elem.innerHTML = "x is " + x + " and y is " + y;
var y = 7;
</script>

• This is because only the declaration (var y), not the initialization (=7) is hoisted to the
top.
• Because of hoisting, y has been declared before it is used, but because initializations are
not hoisted, the value of y is undefined.
• Note : Declare Your Variables At the Top !
• JavaScript in strict mode does not allow variables to be used if they are not declared.

Function Hoisting
Hoisting applies to function declarations. Because of this, JavaScript functions can be called
before they are declared.
myFunction(5);
function myFunction(y) {
return y * y;
}
Functions defined using an expression are not hoisted.

Use Strict
"use strict"; Defines that JavaScript code should be executed in "strict mode".
Declaring Strict Mode

• Strict mode is declared by adding "use strict"; to the beginning of a script or a function.
• Declared at the beginning of a script, it has global scope (all code in the script will
execute in strict mode)
"use strict";
x = 3.14; // This will cause an error because x is not declared "use strict";

myFunction();
function myFunction() {
y = 3.14; // This will also cause an error because y is not declared
}
Declared inside a function, it has local scope (only the code inside the function is in strict
mode):
x = 3.14; // This will not cause an error.
myFunction();
function myFunction() {
"use strict";
y = 3.14; // This will cause an error
}

Why Strict Mode?

• Strict mode makes it easier to write "secure" JavaScript.


• Strict mode changes previously accepted "bad syntax" into real errors.
• As an example, in normal JavaScript, mistyping a variable name creates a new global
variable. In strict mode, this will throw an error, making it impossible to accidentally
create a global variable.
• In normal JavaScript, a developer will not receive any error feedback assigning values to
non-writable properties.
• In strict mode, any assignment to a non-writable property, a getter-only property, a
non-existing property, a non-existing variable, or a non-existing object, will throw an
error.

Not Allowed in Strict Mode


• Using a variable, without declaring it, is not allowed.
• Using an object, without declaring it, is not allowed.
• Deleting a variable (or object) is not allowed.
• Deleting a function is not allowed.
• Duplicating a parameter name is not allowed.
• Octal numeric literals are not allowed.
• Octal escape characters are not allowed.
• Writing to a read-only property is not allowed.
• Writing to a get-only property is not allowed.
• Deleting an undeletable property is not allowed.
• The word eval cannot be used as a variable.
• The word arguments cannot be used as a variable.
• The with statement is not allowed.

Keywords reserved for future JavaScript versions can NOT be used as variable names in strict
mode.
These are:

• Implements
• interface
• let
• package
• private
• protected
• public
• static
• yield

HTML DOM (Document Object Model)


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:
• The HTML elements as objects
• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements
In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML
elements.
The HTML DOM model is constructed as a tree of Objects.

The DOM Programming Interface

• The HTML DOM can be accessed with JavaScript (and with other programming
languages).
• In the DOM, all HTML elements are defined as objects.
• The programming interface is the properties and methods of each object.
• A property is a value that you can get or set (like changing the content of an HTML
element).
• A method is an action you can do (like add or deleting an HTML element).
Finding HTML Elements

Method Description

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

document.getElementsByTagName(name) Find elements by tag name

document.getElementsByClassName(name) Find elements by class name

Changing HTML Elements

Property Description

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

Change the attribute value of an HTML


element.attribute = new value
element

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

Method Description

Change the attribute value of an HTML


element.setAttribute(attribute, value)
element

Adding and Deleting Elements

Method Description

document.createElement(element) Create an HTML element


document.removeChild(element) Remove an HTML element

document.appendChild(element) Add an HTML element

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

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

Adding Events Handlers

Method Description

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


function(){code} event

Add Many Event Handlers to the Same Element


<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to add many events on the same
button.</p>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
var x = document.getElementById("myBtn");
x.addEventListener("mouseover", myFunction);
x.addEventListener("click", mySecondFunction);
x.addEventListener("mouseout", myThirdFunction);
function myFunction() {
document.getElementById("demo").innerHTML += "Moused over!<br>";
}
function mySecondFunction() {
document.getElementById("demo").innerHTML += "Clicked!<br>";
}
function myThirdFunction() {
document.getElementById("demo").innerHTML += "Moused out!<br>";
}
</script>
</body>
</html>

Add an Event Handler to the window Object


The addEventListener() method allows you to add event listeners on any HTML DOM object
such as HTML elements, the HTML document, the window object, or other objects that support
events, like the xmlHttpRequest object.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method on the window object.</p>
<p>Try resizing this browser window to trigger the "resize" event handler.</p>
<p id="demo"></p>
<script>
window.addEventListener("resize", function(){
document.getElementById("demo").innerHTML = Math.random();
});
</script>
</body>
</html>

Event Propagation
It determines in which order the elements receive the event. There are two ways to handle this
event propagation order of HTML DOM is Event Bubbling and Event Capturing.
With the addEventListener() method you can specify the propagation type by using the
"useCapture" parameter:
addEventListener(event, function, useCapture);
The default value is false, which will use the bubbling propagation, when the value is set to
true, the event uses the capturing propagation.

Event Bubbling
When an event happens on a component, it first runs the event handler on it, then on its parent
component, then all the way up on other ancestors’ components. By default, all event handles
through this order from center component event to outermost component event.
<!DOCTYPE html>
<html>
<head>
<style>
#div1 {
background-color: lightgreen;
padding: 24px;
border: 1px solid black;
}
#div2 {
background-color: yellow;
padding: 18px;
border: 1px solid black;
}
#div3 {
background-color: orange;
border: 1px solid black;
}
</style>
</head>
<body>
<h1>Event Bubbling</h1>
<div id="div1">
Component 1
<div id="div2">
component 2
<div id="div3">
component 3
</div>
</div>
</div>
<!-- Javascript code for event bubbling -->
<script>
let div1 = document.querySelector("#div1");
let div2 = document.querySelector("#div2");
let div3 = document.querySelector("#div3");
div1.addEventListener("click", function (event) {
alert("Component 1 event clicked");
});
div2.addEventListener("click", function (event) {
alert("Component 2 event clicked");
});
div3.addEventListener("click", function (event) {
alert("Component 3 event clicked");
});
</script>
</body>
</html>

Event Capturing
It is the opposite of bubbling. The event handler is first on its parent component and then on
the component where it was actually wanted to fire that event handler. In short, it means that
the event is first captured by the outermost element and propagated to the inner elements. It is
also called trickle down.
<!DOCTYPE html>
<html>
<head>
<style>
#div1 {
background-color: lightgreen;
padding: 24px;
border: 1px solid black;
}
#div2 {
background-color: yellow;
padding: 18px;
border: 1px solid black;
}
#div3 {
background-color: orange;
border: 1px solid black;
}
</style>
</head>
<body>
<h1>Event Capturing</h1>
<div id="div1">
Component 1
<div id="div2">
component 2
<div id="div3">
component 3
</div>
</div>
</div>
<!-- Javascript code for event capturing -->
<script>
let div1 = document.querySelector("#div1");
let div2 = document.querySelector("#div2");
let div3 = document.querySelector("#div3");
div1.addEventListener("click", function (event) {
alert("Component 1 event clicked");
}, true);
div2.addEventListener("click", function (event) {
alert("Component 2 event clicked");
}, true);
div3.addEventListener("click", function (event) {
alert("Component 3 event clicked");
}, true);
</script>
</body>
</html>

JavaScript Callbacks
• A callback is a function passed as an argument to another function.
• This technique allows a function to call another function.
• A callback function can run after another function has finished.

<!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>

Sequence Control
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<h2>Function Sequence</h2>
<p>JavaScript functions are executed in the sequence they are called.</p>
<p>The result of the calculation is:</p>
<p id="demo"></p>
<script>
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
function myCalculator(num1, num2) {
let sum = num1 + num2;
myDisplayer(sum);
}
myCalculator(5, 5);
</script>
</body>
</html>

The problem with the first example above, is that you have to call two functions to display the
result.
The problem with the second example, is that you cannot prevent the calculator function from
displaying the result.

Callback Function
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<h2>Callback Functions</h2>
<p>The result of the calculation is:</p>
<p id="demo"></p>
<script>
function myDisplayer(something) {
document.getElementById("demo").innerHTML = something;
}
function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, myDisplayer);
</script>
</body>
</html>
• myDisplayer is a called a callback function.
• It is passed to myCalculator() as an argument.
• When you pass a function as an argument, remember not to use parenthesis.

JSON
• JSON stands for JavaScript Object Notation
• JSON is a lightweight data-interchange format
• JSON is plain text written in JavaScript object notation
• JSON is used to send data between computers
• JSON is language independent
• The JSON syntax is derived from JavaScript object notation, but the JSON format is text
only.
• Code for reading and generating JSON exists in many programming languages.
• The JSON format was originally specified by Douglas Crockford.

JSON Syntax Rules


JSON syntax is derived from JavaScript object notation syntax:
• Data is in name/value pairs
• Data is separated by commas
• Curly braces hold objects
• Square brackets hold arrays

JSON Data Types


In JSON, values must be one of the following data types:
• a string
• a number
• an object
• an array
• a boolean
• null
In JavaScript values can be all of the above, plus any other valid JavaScript expression,
including:
• a function
• a date
• undefined
In JSON, string values must be written with double quotes.
JSON - {"name" : "John"}
JavaScript - { name : "John" }

JSON vs XML
Both JSON and XML can be used to receive data from a web server.
JSON XML
<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</lastName>
{"employees":[ </employee>
{ "firstName":"John", "lastName":"Doe" }, <employee>
{ "firstName":"Anna", "lastName":"Smith" }, <firstName>Anna</firstName> <lastName>Smith</lastName>
{ "firstName":"Peter", "lastName":"Jones" } </employee>
]} <employee>
<firstName>Peter</firstName> <lastName>Jones</lastName>
</employee>
</employees>

JSON is Like XML Because


• Both JSON and XML are "self-describing" (human readable)
• Both JSON and XML are hierarchical (values within values)
• Both JSON and XML can be parsed and used by lots of programming languages
• Both JSON and XML can be fetched with an XMLHttpRequest

JSON is Unlike XML Because


• JSON doesn't use end tag
• JSON is shorter
• JSON is quicker to read and write
• JSON can use arrays

The biggest difference is:


XML has to be parsed with an XML parser. JSON can be parsed by a standard JavaScript
function.

Why JSON is Better than XML


XML is much more difficult to parse than JSON.
JSON is parsed into a ready-to-use JavaScript object.
For AJAX applications, JSON is faster and easier than XML:
Using XML
• Fetch an XML document
• Use the XML DOM to loop through the document
• Extract values and store in variables
Using JSON
• Fetch a JSON string
• JSON.Parse the JSON string

JSON.parse()

• A common use of JSON is to exchange data to/from a web server.


• When receiving data from a web server, the data is always a string.
• Parse the data with JSON.parse(), and the data becomes a JavaScript object.

<h2>Creating an Object from a JSON String</h2>


<p id="demo"></p>
<script>
const txt = '{"name":"John", "age":30, "city":"New York"}'
const obj = JSON.parse(txt);
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
</script>

<h2>Parsing a JSON Array.</h2>


<p>Data written as an JSON array will be parsed into a JavaScript array.</p>
<p id="demo"></p>
<script>
const text = '[ "Ford", "BMW", "Audi", "Fiat" ]';
const myArr = JSON.parse(text);
document.getElementById("demo").innerHTML = myArr[0];
</script>

Note : You should avoid using functions in JSON, the functions will lose their scope, and you
would have to use eval() to convert them back into functions.

JSON.stringify()

• A common use of JSON is to exchange data to/from a web server.


• When sending data to a web server, the data has to be a string.
• Convert a JavaScript object into a string with JSON.stringify().

<h2>Create a JSON string from a JavaScript object.</h2>


<p id="demo"></p>
<script>
const obj = {name: "John", age: 30, city: "New York"};
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>

<h2>Create a JSON string from a JavaScript array.</h2>


<p id="demo"></p>
<script>
const arr = ["John", "Peter", "Sally", "Jane"];
const myJSON = JSON.stringify(arr);
document.getElementById("demo").innerHTML = myJSON;
</script>

Note : If you send functions using JSON, the functions will lose their scope, and the receiver
would have to use eval() to convert them back into functions.

Sending Data to Server

Asynchronous JavaScript
• Functions running in parallel with other functions are called asynchronous.
• A good example is JavaScript setTimeout().

Waiting for a Timeout


When using the JavaScript function setTimeout(), you can specify a callback function to be
executed on time-out:
<h1>JavaScript Functions</h1>
<h2>setTimeout() with a Callback</h2>
<p>Wait 3 seconds…</p>
<h1 id="demo"></h1>
<script>
setTimeout(myFunction, 3000);
function myFunction() {
document.getElementById("demo").innerHTML = "I am using asynchronous JS!!";
}
</script>

Waiting for Intervals:


When using the JavaScript function setInterval(), you can specify a callback function to be
executed for each interval:
<h1>JavaScript Functions</h1>
<h2>setInterval() with a Callback</h2>
<p>Using setInterval() to display the time every second…</p>
<h1 id="demo"></h1>
<script>
setInterval(myFunction, 1000);
function myFunction() {
let d = new Date();
document.getElementById("demo").innerHTML=
d.getHours() + ":" +
d.getMinutes() + ":" +
d.getSeconds();
}
</script>

Example
<p id="demo"></p>
<script>
const data = [
{ name: "ABC", age: 25 },
{ name: "XYZ", age: 30 },
];
function getData() {
setTimeout(() => {
let output = "";
data.forEach((data, index) => {
output += `<li>${data.name}</li>`;
});
document.getElementById("demo").innerHTML = output;
}, 1000);
}
function createData(newData) {
setTimeout(() => {
data.push(newData);
}, 2000);
}
getData();
createData({ name: "DEF", age: 28 });
</script>

Changes for Callback


function createData(newData, callback) {
setTimeout(() => {
data.push(newData);
callback();
}, 2000);
}
createData({ name: "DEF", age: 28 }, getData);

Callback Alternatives

• With asynchronous programming, JavaScript programs can start long-running tasks, and
continue running other tasks in parallel.
• But, asynchronous programs are difficult to write and difficult to debug.
• Because of this, most modern asynchronous JavaScript methods don't use callbacks.
Instead, in JavaScript, asynchronous programming is solved using Promises instead.

JavaScript Promises
A promise is an object that encapsulates the result of an asynchronous operation.
A Promise contains both the producing code and calls to the consuming code.

• Producing code is code that can take some time


• Consuming code is code that must wait for the result
• A Promise is an Object that links Producing code and Consuming code

Promise Syntax
let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)
myResolve(); // when successful
myReject(); // when error
});

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


myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
A promise object has a state that can be one of the following:
• Pending
• Fulfilled with a value
• Rejected for a reason
In the beginning, the state of a promise is pending, indicating that the asynchronous operation
is in progress. Depending on the result of the asynchronous operation, the state changes to
either fulfilled or rejected.
You cannot access the Promise properties state and result. You must use a Promise method to
handle promises.

Example
<p id="demo"></p>
<script>
const data = [
{ name: "ABC", age: 25 },
{ name: "XYZ", age: 30 },
];

function getData() {
setTimeout(() => {
let output = "";
data.forEach((data, index) => {
output += `<li>${data.name}</li>`;
});
document.getElementById("demo").innerHTML = output;
}, 1000);
}
function createData(newData) {
return new Promise((resolve, reject) => {
setTimeout(() => {
data.push(newData);
let error = false;
if(!error) {
resolve();
} else {
reject("Error in getting Data");
}
callback();
}, 2000);
});
}

createData({ name: "DEF", age: 28 })


.then(getData);
</script>

Using Catch for Errors


createData({ name: "DEF", age: 28 })
.then(getData)
.catch(err => console.log(err));

JavaScript Async/Await
• async and await make promises easier to write
• async makes a function return a Promise
• await makes a function wait for a Promise
Syntax
async function name(parameter1, parameter2, ...paramaterN) {
// statements
}

Waiting for a Timeout


<h1>JavaScript async / await</h1>
<h2 id="demo"></h2>
<p>Wait 3 seconds...</p>
<script>
async function myDisplay() {
let myPromise = new Promise(function(resolve) {
setTimeout(function() {resolve("I am using Asynchronous JS!!");}, 3000);
});
document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();
</script>

Example
async function start() {
await createData({ name: "DEF", age: 28 });
getData();
}
start();
AJAX
• AJAX is an acronym for Asynchronous JavaScript and XML.
• AJAX allows you to send and receive data asynchronously without reloading the web
page. So it is fast.
• AJAX allows you to send only important information to the server not the entire page.
So only valuable data from the client side is routed to the server side. It makes your
application interactive and faster.

Advantages Disadvantages

• Good compatibility. • More cumbersome to operate.


• Allows for multiple requests. • Handling cross-domain issues can be a
• Supports canceling requests and significant problem.
progress tracking. • Difficult to handle JSON data.

Synchronous (Classic Web-Application Model)


A synchronous request blocks the client until operation completes i.e. browser is unresponsive.
In such case, JavaScript engine of the browser is blocked.

Asynchronous (AJAX Web-Application Model)


An asynchronous request doesn’t block the client i.e. browser is responsive. At that time, user
can perform another operations also. In such case, JavaScript engine of the browser is not
blocked.

AJAX Technologies
It is not a technology but group of inter-related technologies.

These technologies are used for displaying content and style. It is


HTML/XHTML and CSS
mainly used for presentation.

DOM It is used for dynamic display and interaction with data.

For carrying data to and from server. JSON (JavaScript Object


XML or JSON
Notation) is like XML but short and faster than XML.
For asynchronous communication between client and server. For
XMLHttpRequest
more visit next page.

It is used to bring above technologies together.


JavaScript
Independently, it is used mainly for client-side validation.

Understanding XMLHttpRequest
An object of XMLHttpRequest is used for asynchronous communication between client and
server.
It performs following operations:

• Sends data from the client in the background


• Receives the data from the server
• Updates the webpage without reloading it.

How AJAX works?


As you can see in the above example, XMLHttpRequest object plays a important role.
1. User sends a request from the UI and a javascript call goes to XMLHttpRequest object.
2. HTTP Request is sent to the server by XMLHttpRequest object.
3. Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
4. Data is retrieved.
5. Server sends XML data or JSON data to the XMLHttpRequest callback function.
6. HTML and CSS data is displayed on the browser.

AJAX Example

Fetch API
The Fetch API interface allows web browser to make HTTP requests to web servers.

Similarities Between AJAX and Fetch API

• Both use technology to send HTTP requests via the internet.


• Support asynchronous requests.
• Can handle different types of data formats, such as JSON, XML, HTML, etc.
• Can set headers to send additional information.
• Support using Promise or async/await to handle asynchronous request responses.

Advantages Disadvantages
• More modern and standardized, with • Poor compatibility, requiring the use
built-in Promise API for simplicity and of polyfills or special processing.
readability. • Does not support canceling requests.
• Supports cross-domain requests. • Does not support progress tracking.
• Convenient for handling JSON data.
• Can be configured with more options,
such as headers, method, mode,
cache, etc.

Fetch API Syntax


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

In this example, we're fetching data from https://api.example.com/data. The then() method is
used to handle the response, converting it to JSON using the json() method. The
second then() block logs the retrieved data to the console, and the catch() block handles errors
if the request fails.

Fetch API Example

You might also like