Module 2
Module 2
Javascript
Introduction to Javascript
• JavaScript is a lightweight, cross-platform, and interpreted
compiled programming language which is also known as the
scripting language for webpages.
• It is well-known for the development of web pages, many non-
browser environments also use it.
• JavaScript can be used for Client-side developments as well as
Server-side developments.
• Javascript is both imperative and declarative type of language.
• JavaScript contains a standard library of objects, like Array, Date,
and Math, and a core set of language elements
like operators, control structures, and statements.
Client-side:
• It supplies objects to control a browser and its Document Object
Model (DOM).
• Like if client-side extensions allow an application to place
elements on an HTML form and respond to user events such
as mouse clicks, form input, and page navigation.
• Useful libraries for the client-side are AngularJS, ReactJS
, VueJS and so many others.
Server-side:
• It supplies objects relevant to running JavaScript on a server.
• Like if the server-side extensions allow an application to
communicate with a database, and provide continuity of
information from one invocation to another of the application, or
perform file manipulations on a server.
• The useful framework which is the most famous these days is
node.js.
Imperative language –
• In this type of language we are mostly concern about how it is to
be done .
• It simply control the flow of computation .
• The procedural programming approach , object, oriented approach
comes under this like async await we are thinking what it is to be
done further after async call.
Declarative programming –
• In this type of language we are concern about how it is to be
done .
• Basically here logical computation require .
• Here main goal is to describe the desired result without direct
dictation on how to get it like arrow function do .
JavaScript can be added to your HTML file in two ways:
Internal JS:
We can add JavaScript directly to our HTML file by writing the code
inside the <script> tag. The <script> tag can either be placed inside
the <head> or the <body> tag according to the requirement.
External JS:
We can write JavaScript code in other file having an extension.js and
then link this file inside the <head> tag of the HTML file in which we
want to add this code.
Applications of JavaScript:
• Web Development
• Web Applications
• Server Applications
• Games
• Smartwatches
• Art
• Machine Learning
• Mobile Applications
Limitations of JavaScript:
Security risks: JavaScript can be used to fetch data using AJAX or by manipulating tags
that load data such as <img>, <object>, <script>. These attacks are called cross site script
attacks. They inject JS that is not the part of the site into the visitor’s browser thus
fetching the details.
Performance: JavaScript does not provide the same level of performance as offered by
many traditional languages as a complex program written in JavaScript would be
comparatively slow.
Complexity: To master a scripting language, programmers must have a thorough
knowledge of all the programming concepts, core language objects, client and server-
side objects otherwise it would be difficult for them to write advanced scripts using
JavaScript.
Weak error handling and type checking facilities: It is weakly typed language as there is
no need to specify the data type of the variable. So wrong type checking is not
performed by compile.
JavaScript Language constructs
• Values
• Variables
• Constants
• Literals
• Functions
Values
• Values that JavaScript recognizes and describes the
fundamental building blocks of JavaScript expressions:
variables, constants, and literals.
Evaluating variables –
• A variable declared using the var statement with no initial
value specified has the value undefined.
• An attempt to access an undeclared variable will result in a
ReferenceError exception being thrown:
var a;
console.log(“The value of a is ” + a); // prints “The value of a is
undefined”
console.log(“The value of b is ” + b); // throws ReferenceError
exception
Variable scope – Depending upon where a variable is used, it can be
Local –
• It is a variable declared within a JavaScript function becomes LOCAL
and can only be accessed within that function.
• Local variables with the same name in different functions can be
present, because local variables are only recognized by the function
in which they are declared.
Global –
• It is declaring a variable outside of any function, because it is
available to any other code in the current document.
Constants
• We can create a read-only, named constant with the const
keyword.
• The syntax of a constant identifier is the same as for a variable
identifier: it must start with a letter or underscore and can contain
alphabetic, numeric, or underscore characters.
Array literals –
• An array literal is a list of zero or more expressions, each of which represents an array
element, enclosed in square brackets ([]).
• When you create an array using an array literal, it is initialized with the specified values
as its elements, and its length is set to the number of arguments specified.
• The following example creates coffees array with three elements and a length of three:
var coffees = [“French Roast”, “Colombian”, “Kona”];
Boolean literals – The Boolean type has two literal values: true and false.
Object literals –
• An object literal is a list of zero or more pairs of property names and associated
values of an object, enclosed in curly braces ({}).
• You should not use an object literal at the beginning of a statement.
• This will lead to an error or not behave as you expect, because the { will be
interpreted as the beginning of a block. It is a comma separated list of name
value pairs wrapped in curly braces.
• It is declared or defined as:
var myObject = {}
Functions –
• A function is a block of code that executes only when you tell it to execute.
• It can be when an event occurs, like when a user clicks a button, or from a call within
your script, or from a call within another function.
• Functions can be placed both in the <head> and in the <body> section of a web page.
1. Math Object
Math object is a built-in static object.
It is used for performing complex math operations.
Math Properties
Math Methods
Example: Simple Program on Math Object Methods
<html>
<head>
<title>JavaScript Math Object Methods</title>
</head>
<body>
<script type="text/javascript">
</script>
</body>
</html>
Output
ABS Test Value : 20
ACOS Test Value : 3.141592653589793
Example: Simple Program on Math Object Properties
<html>
<head>
<title>JavaScript Math Object Properties</title>
</head>
<body>
<script type="text/javascript">
var value1 = Math.E
document.write("E Value is :" + value1 + "<br>");
</script>
</body>
</html>
Output:
E Value is :2.718281828459045
LN2 Value is :0.6931471805599453
2. Date Object
Example:
var current_date = new Date();
Date Methods
Example : JavaScript Date() Methods Program
<html>
<body>
<center>
<h2>Date Methods</h2>
<script type="text/javascript">
var d = new Date();
document.write("<b>Locale String:</b> " + d.toLocaleString()+"<br>");
document.write("<b>Hours:</b> " + d.getHours()+"<br>");
document.write("<b>Day:</b> " + d.getDay()+"<br>");
document.write("<b>Month:</b> " + d.getMonth()+"<br>");
document.write("<b>FullYear:</b> " + d.getFullYear()+"<br>");
document.write("<b>Minutes:</b> " + d.getMinutes()+"<br>");
</script>
</center>
</body>
</html> Output:
3. String Object
Syntax:
var variable_name = new String(string);
Example:
var s = new String(string);
String Properties
Properties Description
length It returns the length of the string.
prototype It allows you to add properties and
methods to an object.
constructor It returns the reference to the String
function that created the object.
String Methods
Methods Description
charAt() It returns the character at the specified index.
<form>
<input type="button" value="Open Window" onclick="openWin()">
</form>
</body>
</html>
Close the new window
<!DOCTYPE html>
<html>
<head>
<script>
var myWindow;
function openWin() {
myWindow = window.open("", "", "width=400, height=200");
}
function closeWin() {
myWindow.close();
}
</script>
</head>
<body>
</body>
</html>
Write some text to the source (parent)
window
<!DOCTYPE html>
<html>
<head>
<script>
function openWin() {
var myWindow = window.open("", "", "width=400, height=200");
myWindow.opener.document.getElementById("demo").innerHTML =
"A new window has been opened.";
}
</script>
</head>
<body>
<p id="demo"></p>
</body>
</html>
Print the current page
<!DOCTYPE html>
<html>
<head>
<script>
function printPage() {
window.print();
}
</script>
</head>
<body>
</body>
</html>
Screen Object
Screen Object
The Visitors Screen: Width and Height
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<p id="dem"></p>
<script>
document.getElementById("demo").innerHTML =
"Screen width is " + screen.width;
document.getElementById("dem").innerHTML =
"Screen height is " + screen.height;
</script>
</body>
</html>
The Visitors screen: Pixel Depth
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"Screen pixel depth is " + screen.pixelDepth;
</script>
</body>
</html>
Location Object
Location Object
Return the hostname of the current URL
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"Page hostname is: " + window.location.hostname;
</script>
</body>
</html>
Return the path name of the current URL
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"Page path is: " + window.location.pathname;
</script>
</body>
</html>
Load a new document
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript</h2>
<script>
function newDoc() {
window.location.assign("https://www.w3schools.com")
}
</script>
</body>
</html>
History Object
History Object
Display the number of URL in the history list
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = history.length;
}
</script>
</body>
</html>
Create a back button on a page
<!DOCTYPE html>
<html>
<head>
<script>
function goBack() {
window.history.back()
}
</script>
</head>
<body>
<p>Clicking on the Back button here will not result in any action, because there is no
previous URL in the history list.</p>
</body>
</html>
Navigator Object
Navigator Object
Is cookies enabled in the visitors browser
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"navigator.cookieEnabled is " + navigator.cookieEnabled;
</script>
</body>
</html>
What is the name of the visitors browser
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Navigator</h2>
<p>Do not rely on it! "Mozilla" is the application code name for Chrome, Firefox, IE,
Safari, and Opera.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"navigator.appCodeName is " + navigator.appCodeName;
</script>
</body>
</html>
JavaScript Event handling
• HTML events are "things" that happen to HTML elements.
• When JavaScript is used in HTML pages, JavaScript can "react" on these events.
HTML Events
An HTML event can be something the browser does, or something a user does.
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">
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>
</body>
</html>
JavaScript Form Validation
• HTML form validation can be done by JavaScript.
• If a form field (fname) is empty, this function alerts a
message, and returns false, to prevent the form from being
submitted:
JavaScript Example
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
<h2>JavaScript Validation</h2>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Validation</h2>
<p>If you click submit, without filling out the text field,
your browser will display an error message.</p>
</body>
</html>
Data Validation
• Data validation is the process of ensuring that user input is clean, correct, and
useful.
• When a browser requests a web page from a server, cookies belonging to the page are
added to the request. This way the server gets the necessary data to "remember"
information about users.
Create a Cookie with JavaScript
• JavaScript can create, read, and delete cookies with the document.cookie property.
• You can also add an expiry date (in UTC time). By default, the cookie is deleted when
the browser is closed:
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";
• With a path parameter, you can tell the browser what path the cookie belongs to. By
default, the cookie belongs to the current page.
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC;
path=/";
Read a Cookie with JavaScript
• With JavaScript, cookies can be read like this:
let x = document.cookie;
• document.cookie will return all cookies in one string much like: cookie1=value;
cookie2=value; cookie3=value;
Data-types ES5 supports primitive data types that are string, In ES6, there are some additions to JavaScript data
number, boolean, null, and undefined. types. It introduced a new primitive data
type 'symbol' for supporting unique values.
Defining Variables In ES5, we could only define the variables by using In ES6, there are two new ways to define variables
the var keyword. that are let and const.
Performance As ES5 is prior to ES6, there is a non-presence of Because of new features and the shorthand storage
some features, so it has a lower performance than implementation ES6 has a higher performance than
ES6. ES5.
Support A wide range of communities supports it. It also has a lot of community support, but it is lesser
than ES5.
Object Manipulation ES5 is time-consuming than ES6. Due to destructuring and speed operators, object
manipulation can be processed more smoothly in
ES6.
Arrow Functions In ES5, both function and return keywords are used An arrow function is a new feature introduced in
to define a function. ES6 by which we don't require the function keyword
to define the function.
Loops In ES5, there is a use of for loop to iterate over ES6 introduced the concept of for...of loop to
elements. perform an iteration over the values of the iterable
objects.
JavaScript Variables
4 Ways to Declare a JavaScript Variable:
1. Using var
2. Using let
3. Using const
4. Using nothing
What are Variables?
Variables are containers for storing data (storing data values).
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>In this example, x, y, and z are variables.</p>
<p id="demo"></p>
<script>
var x = 5;
var y = 6;
let z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>
</body>
</html>
Conditional Statements
Very often when you write code, you want to perform different actions for different
decisions.
</body>
</html>
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
}
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if .. else</h2>
<p>A time-based <p id="demo"></p>greeting:</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>
</body>
</html>
The else if Statement
Use the else if statement to specify a new condition if the first condition is false.
Syntax
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
}
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if .. else</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>
</body>
</html>
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
}
<!DOCTYPE html>
<html>
<body>
<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>
</body>
</html>
Loops
<p id="demo"></p>
<script>
let text = "";
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
The For In Loop
The JavaScript for in statement loops through the properties of an Object:
Syntax
for (key in object) {
// code block to be executed
}
<!DOCTYPE html>
<html>
<body>
<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>
</body>
</html>
The 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);
<!DOCTYPE html>
<html>
<body>
<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>
</body>
</html>
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: {}
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
<!DOCTYPE html>
<html>
<body><h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation and returns the result:</p>
<p id="demo"></p>
<script>
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
</script>
</body>
</html>
JavaScript Event
• HTML events are "things" that happen to HTML elements.
• When JavaScript is used in HTML pages, JavaScript can "react" on these events.
HTML 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">
<!DOCTYPE html>
<html>
<body>
<button onclick="document.getElementById('demo').innerHTML=Date()">The time
is?</button>
<p id="demo"></p>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML Events</h2>
<button onclick="this.innerHTML=Date()">The time is?</button>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML Events</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 Arrow Function
• Arrow functions were introduced in ES6.
• Arrow functions allow us to write shorter function syntax:
<!DOCTYPE html>
<html>
<body>
<p>This example shows the syntax of an Arrow Function, and how to use it.</p>
<p id="demo"></p>
<script>
let myFunction = (a, b) => a * b;
document.getElementById("demo").innerHTML = myFunction(4, 5);
</script>
</body>
</html>
Before:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Function</h2>
<p>This example shows the syntax of a function, without the use of arrow function
syntax.</p>
<p id="demo"></p>
<script>
var hello;
hello = function() {
return "Hello World!";
}
document.getElementById("demo").innerHTML = hello();
</script>
</body>
</html>
With Arrow Function:
<!DOCTYPE html>
<html>
<body>
<p>This example shows the syntax of an Arrow Function, and how to use it.</p>
<p id="demo"></p>
<script>
var hello;
hello = () => {
return "Hello World!";
}
document.getElementById("demo").innerHTML = hello();
</script>
</body>
</html>
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:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrow Function</h2>
<p>This example shows an Arrow Function without the brackets or the return
keyword.</p>
<p id="demo"></p>
<script>
var hello;
document.getElementById("demo").innerHTML = hello();
</script>
</body>
</html>
Note: This works only if the function has only one statement.
If you have parameters, you pass them inside the parentheses:
Arrow Function With Parameters:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var hello;
document.getElementById("demo").innerHTML = hello("Universe!");
</script>
</body>
</html>
In fact, if you have only one parameter, you can skip the parentheses as well:
Arrow Function Without Parentheses:
<!DOCTYPE html>
<html>
<body>
<p>This example shows that if you have only one parameter in an Arrow Function, you can
skip the parentheses.</p>
<p id="demo"></p>
<script>
var hello;
document.getElementById("demo").innerHTML = hello("Universe!");
</script>
</body>
</html>
Setting CSS Styles using JavaScript
CSS Styles
Classes and Inheritance
• HTML DOM methods are actions you can perform (on HTML Elements).
• HTML DOM properties are values (of HTML Elements) that you can set or change.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
• The most common way to access an HTML element is to use the id of the element.
• In the example above the getElementById method used id="demo" to find the element.
• The easiest way to get the content of an element is by using the innerHTML property.
• The innerHTML property is useful for getting or replacing the content of HTML elements.
• The innerHTML property can be used to get or change any HTML element,
including <html> and <body>.
Iterators and generators
const it = array[Symbol.iterator]();
document.write(JSON.stringify(it.next()));
//{ value: "a", done: false } Output:{"value":"a","done":false}
{"value":"b","done":false}
document.write(JSON.stringify(it.next())); {"value":"c","done":false}{"done":true}
//{ value: "b", done: false }
document.write(JSON.stringify(it.next()));
//{ value: "c", done: false }
document.write(JSON.stringify(it.next()));
/* Actual it.next() will be { value: undefined,
done: true } but here you will get
{done: true} output because of JSON.stringify
as it omits undefined values*/
</script>
• Using for.of loop, we can iterate over any entity (for eg: object) which follows iterable
protocol.
• The for.of loop is going to pull out the value that gets a return by calling the next()
method each time.
<script>
<script>
const array = ['a', 'b', 'c'];
const array = ['a', 'b', 'c'];
const it = array[Symbol.iterator]();
const it = array[Symbol.iterator]();
for (let value of it)
for (let value of it)
{
{
document.write(value)
document.write(value)
}
}
const arr = ['d', 'e', 'f'];
</script>
const it1 = arr[Symbol.iterator]();
Output:
for (let value of it1)
{
abc
document.write(value)
}
</script>
Generator
Generator-Function :
• A generator-function is defined like a normal function,
• but whenever it needs to generate a value, it does so with the yield keyword rather than
return.
• The yield statement suspends function’s execution and sends a value back to caller,
• but retains enough state to enable function to resume where it is left off.
• When resumed, the function continues execution immediately after the last yield run.
Syntax :
// An example of generator function
function* gen(){
yield 1;
yield 2;
...
...
}
Generator-Object :
• Generator functions return a generator object.
• Generator objects are used either by calling the next method
on the generator object or using the generator object in a “for
of” loop
• The Generator object is returned by a generating function and
it conforms to both the iterable protocol and the iterator
protocol.
<script>
// Generate Function generates three
// different numbers in three calls
function * fun()
{
yield 10;
yield 20;
yield 30;
}
const it = generator(array);
</script>
Encountering yield and yield* syntax
yield: pauses the generator execution and returns the value of the expression which is
being written after the yield keyword.
yield*: it iterates over the operand and returns each value until done is true.
<script>
function* generator() {
Output
yield 1;
yield* arr;
1abc2
yield 2;
}
</script>
Promises
• Promises are used to handle asynchronous operations in
JavaScript.
• They are easy to manage when dealing with multiple asynchronous
operations where callbacks can create callback hell leading to
unmanageable code.
• Prior to promises events and callback functions were used but they
had limited functionalities and created unmanageable code.
• Promises are the ideal choice for handling asynchronous
operations in the simplest manner.
• They can handle multiple asynchronous operations easily and
provide better error handling than callbacks and events.
• Promises do provide a better chance to a user to read the code in a
more effective and efficient manner especially it that particular
code is used for implementing multiple asynchronous operations
Benefits of Promises
• Improves Code Readability
• Better handling of asynchronous operations
• Better flow of control definition in asynchronous logic
• Better Error Handling
Syntax
Parameters
• Promise constructor takes only one argument which is a callback function (and
that callback function is also referred as anonymous function too).
• Callback function takes two arguments, resolve and reject
• Perform operations inside the callback function and if everything went well then
call resolve.
• If desired operations do not go well then call reject.
var promise = new Promise(function(resolve, reject)
{
const x = "geeksforgeeks";
const y = "geeksforgeeks"
if(x === y) {
resolve();
} else {
reject();
}
});
promise.
then(function () {
console.log('Success, You are a GEEK');
}).
catch(function () {
console.log('Some error has occurred');
});
Output:
Success, You are a GEEK
Example: Promise Resolved
var promise = new Promise(function(resolve, reject)
{
resolve('Geeks For Geeks');
})
promise
.then(function(successMessage) {
//success handler function is invoked
console.log(successMessage);
}, function(errorMessage) {
console.log(errorMessage);
})
Promise Rejected
var promise = new Promise(function(resolve, reject)
{
reject('Promise Rejected')
})
promise
.then(function(successMessage) {
console.log(successMessage);
}, function(errorMessage) {
//error handler function is invoked
console.log(errorMessage);
})
Client-server communication
Client-server communication