JavaScript Docs
JavaScript Docs
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>
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
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;
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 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?
• 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>
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
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.
Object Methods
What is this?
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;
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.
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()
replace()
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>
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.
Array Methods
Array Const
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>
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>
• 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.
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 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.
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>
• 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
}
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
• 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
Property Description
Method Description
Method Description
Method Description
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 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.parse()
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()
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.
Asynchronous JavaScript
• Functions running in parallel with other functions are called asynchronous.
• A good example is JavaScript setTimeout().
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>
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.
Promise Syntax
let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)
myResolve(); // when successful
myReject(); // when error
});
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);
});
}
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
}
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
AJAX Technologies
It is not a technology but group of inter-related technologies.
Understanding XMLHttpRequest
An object of XMLHttpRequest is used for asynchronous communication between client and
server.
It performs following operations:
AJAX Example
Fetch API
The Fetch API interface allows web browser to make HTTP requests to web servers.
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.
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.