0% found this document useful (0 votes)
9 views

Module 2

Uploaded by

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

Module 2

Uploaded by

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

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.

JavaScript recognizes the following types of values:


 Numbers, such as 42 or 3.14159
 Logical (Boolean) values, either true or false
 Strings, such as “Howdy!”
 null, a special keyword denoting a null value; null is also a
primitive value.
 undefined, a top-level property whose value is undefined;
undefined is also a primitive value.
Variables
• They are used as symbolic names for values in application.
• The names of variables, called identifiers, conform to certain rules.
• A JavaScript identifier must start with a letter, underscore (_), or
dollar sign ($); subsequent characters can also be digits (0-9).
• Because JavaScript is case sensitive, letters include the characters
“A” through “Z” (uppercase) and the characters “a” through “z”
(lowercase).
• Some examples of legal names are Number_hits, temp99, and
_name.
Declaring variables – It is done in two ways:
• With the keyword var. For example, var x = 42. This syntax can
be used to declare both local and global variables.
• By simply assigning it a value. For example, x = 42. This always
declares a global variable and generates a strict JavaScript
warning.

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.

const prefix = ‘212’;

• A constant cannot change value through assignment or be re-


declared while the script is running.
• The scope rules for constants are the same as those for variables,
except that the const keyword is always required, even for global
constants.
• If the keyword is omitted, the identifier is assumed to represent a
variable.
Literals
It represent values in JavaScript which are fixed values and various types of literals are:

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.

Floating-point literals – A floating-point literal can have the following parts:


• A decimal integer which can be signed (preceded by “+” or “-“),
• A decimal point (“.”),
• A fraction (another decimal number),
• An exponent.
Integers – They can be expressed in decimal (base 10), hexadecimal (base 16), and
octal (base 8).
• Decimal integer literal consists of a sequence of digits without a leading 0 (zero).
• Leading 0 (zero) on an integer literal indicates it is in octal. Octal integers can
include only the digits 0-7.
• Leading 0x (or 0X) indicates hexadecimal. Hexadecimal integers can include
digits (0-9) and the letters a-f and A-F.

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.

Defining a function – The syntax for function definition is


function functionname()
{
some code
}
The { and the } defines the start and end of the function and some code refers to code to be
executed when called.
Function calling and arguments –
• When a function is called, some values can be passed to it, which are called arguments
or parameters.
• These arguments can be used inside the function.
• Multiple arguments can be sent if, separated by commas (,) as
myFunction(argument1,argument2)
Declare the argument, as variables, when you declare the function:
function myFunction(var1,var2)
{
some code
}
Built-in Objects in JavaScript
• Built-in objects are not related to any Window or DOM object model.
• These objects are used for simple data processing in the JavaScript.

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

var value = Math.abs(20);


document.write("ABS Test Value : " + value +"<br>");

var value = Math.acos(-1);


document.write("ACOS Test Value : " + value +"<br>");

</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>");

var value2 = Math.LN2


document.write("LN2 Value is :" + value2 + "<br>");

</script>
</body>
</html>

Output:

E Value is :2.718281828459045
LN2 Value is :0.6931471805599453
2. Date Object

• Date is a data type.


• Date object manipulates date and time.
• Date() constructor takes no arguments.
• Date object allows you to get and set the year, month, day,
hour, minute, second and millisecond fields.
Syntax:
var variable_name = new Date();

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

• String objects are used to work with text.


• It works with a series of characters.

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.

charCodeAt() It returns the ASCII code of the character at the specified


position.
concat() It combines the text of two strings and returns a new string.

indexOf() It returns the index within the calling String object.

match() It is used to match a regular expression against a string.

replace() It is used to replace the matched substring with a new substring.

search() It executes the search for a match between a regular expression.

slice() It extracts a session of a string and returns a new string.

split() It splits a string object into an array of strings by separating the


string into the substrings.

toLowerCase() It returns the calling string value converted lower case.

toUpperCase() Returns the calling string value converted to uppercase.


Example : JavaScript String() Methods Program
<html>
<body>
<center>
<script type="text/javascript">
var str = "CareerRide Info";
var s = str.split();
document.write("<b>Char At:</b> " + str.charAt(1)+"<br>");
document.write("<b>CharCode At:</b> " + str.charCodeAt(2)+"<br>");
document.write("<b>Index of:</b> " + str.indexOf("ide")+"<br>");
document.write("<b>Lower Case:</b> " + str.toLowerCase()+"<br>");
document.write("<b>Upper Case:</b> " + str.toUpperCase()+"<br>");
</script>
<center>
</body>
</html>
JavaScript Browser Objects
• Window Object
• Screen Object
• Location Object
• History Object
• Navigator Object
Window Object
Open New window when clicking on a button
<!DOCTYPE html>
<html>
<head>
<script>
function openWin() {
window.open("https://www.w3schools.com");
}
</script>
</head>
<body>

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

<input type="button" value="Open 'myWindow'" onclick="openWin()" />


<input type="button" value="Close 'myWindow'" onclick="closeWin()" />

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

<button onclick="openWin()">Open myWindow</button>

<p id="demo"></p>

</body>
</html>
Print the current page
<!DOCTYPE html>
<html>
<head>
<script>
function printPage() {
window.print();
}
</script>
</head>
<body>

<input type="button" value="Print this page" onclick="printPage()" />

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

<h3>The window.location object</h3>

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

<h3>The window.location object</h3>

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

<h3>The window.location object</h3>

<input type="button" value="Load new document" onclick="newDoc()">

<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>Display the number of URLs in the history list:</p>

<button onclick="myFunction()">Try it</button>

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

<button onclick="goBack()">Go Back</button>

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

<h2>The Navigator Object</h2>

<p>The cookieEnabled property returns true if cookies are enabled:</p>

<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>The appCodeName property returns the code name of the browser.</p>

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

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

<form name="myForm" action="/action_page.php" onsubmit="return validateForm()"


method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
JavaScript
<!DOCTYPE html>
Can Validate Numeric Input
<html>
<body>
<h2>JavaScript Validation</h2>
<p>Please input a number between 1 and 10:</p>
<input id="numb">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
// Get the value of the input field with id="numb"
let x = document.getElementById("numb").value;
// If x is Not a Number or less than one or greater than 10
let text;
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
Automatic HTML Form Validation
• HTML form validation can be performed automatically by the browser:
• If a form field (fname) is empty, the required attribute prevents this form from being
submitted:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Validation</h2>

<form action="/action_page.php" method="post">


<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>

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

Typical validation tasks are:


• has the user filled in all required fields?
• has the user entered a valid date?
• has the user entered text in a numeric field?
Most often, the purpose of data validation is to ensure correct user input.

Validation can be defined by many different methods, and deployed in many


different ways.
Server side validation is performed by a web server, after input has been sent to
the server.
Client side validation is performed by a web browser, before input is sent to a web
server.
HTML Constraint Validation
• HTML5 introduced a new HTML validation concept called constraint validation.

HTML constraint validation is based on:


• Constraint validation HTML Input Attributes
• Constraint validation CSS Pseudo Selectors
• Constraint validation DOM Properties and Methods
JavaScript Cookies
What are Cookies?
• Cookies are data, stored in small text files, on your computer.
• When a web server has sent a web page to a browser, the connection is shut down,
and the server forgets everything about the user.
• Cookies were invented to solve the problem "how to remember information about the
user":
• When a user visits a web page, his/her name can be stored in a cookie.
• Next time the user visits the page, the cookie "remembers" his/her name.

Cookies are saved in name-value pairs like:


username = John Doe

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

• With JavaScript, a cookie can be created like this:


document.cookie = "username=John Doe";

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

Change a Cookie with JavaScript


• With JavaScript, you can change a cookie the same way as you create it:
document.cookie = "username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC;
path=/";
• The old cookie is overwritten.

Delete a Cookie with JavaScript


• Deleting a cookie is very simple.
• You don't have to specify a cookie value when you delete a cookie.
• Just set the expires parameter to a past date:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Introduction to ES5 andES6
Introduction to ES5
• Syncfusion JavaScript (ES5) 2009 is a modern UI Controls library that has
been built from the ground up to be lightweight, responsive, modular and
touch friendly.
• It is written in TypeScript and has no external dependencies.
• It also includes complete support for Angular, React, Vue, ASP.NET MVC and
ASP.NET Core frameworks.
• The Syncfusion JavaScript (global script) is an ES5 formatted pure JavaScript
framework which can be directly used in latest web browsers.
ES5 Features
1. "use strict"
2. String[number] access
3. Multiline strings
4. String.trim()
5. Array.isArray()
6. Array forEach()
7. Array map()
8. Array filter()
9. Array reduce()
10. Array reduceRight()
11. Array every()
12. Array some()
13. Array indexOf()
14. Array lastIndexOf()
15. JSON.parse()
16. JSON.stringify()
17. Date.now()
18. Date toISOString()
19. Date toJSON()
20. Property getters and setters
21. Reserved words as property names
22. Object methods
Introduction to ES6
• ECMAScript 2015 is also known as ES6 and ECMAScript 6.
• Javascript ES6 has been around for a few years now, and it allows
us to write code in a clever way which basically makes the code
more modern and more readable.
• It’s fair to say that with the use of ES6 features we write less and
do more, hence the term ‘write less, do more’ definitely suits ES6.
• ES6 introduced several key features like const, let, arrow
functions, template literals, default parameters, and a lot more.

ECMA- European Computer Manufacturer's Association


New Features in ES6
1. The let keyword
2. The const keyword
3. Arrow Functions
4. For/of
5. Map Objects
6. Set Objects
7. Classes
8. Promises
9. Symbol
10. Default Parameters
11. Function Rest Parameter
12. String.includes()
13. String.startsWith()
14. String.endsWith()
15. Array.from()
16. Array keys()
17. Array find()
18. Array findIndex()
Based on ES5 ES6
Definition ES5 is the fifth edition of the ECMAScript (a ES6 is the sixth edition of the ECMAScript (a
trademarked scripting language specification defined trademarked scripting language specification defined
by ECMA International) by ECMA International).

Release It was introduced in 2009. It was introduced in 2015.

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.

You can use conditional statements in your code to do this.

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.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
<!DOCTYPE html>
<html>
<body>
<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>

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

JavaScript supports different kinds of loops:

1. for - loops through a block of code a number of times


2. for/in - loops through the properties of an object
3. for/of - loops through the values of an iterable object
4. while - loops through a block of code while a specified condition is true
5. do/while - also loops through a block of code while a specified condition is true
The For Loop
The for statement creates a loop with 3 optional expressions:
for (expression 1; expression 2; expression 3) {
// code block to be executed
}
<!DOCTYPE html>
<html>
<body>

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

<h2>JavaScript For In Loop</h2>


<p>The for in statement loops through the properties of an object:</p>
<p id="demo"></p>
<script>
const person = {fname:"John", lname:"Doe", age:25};

let txt = "";


for (let x in person) {
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
Array.forEach()
The forEach() method calls a function (a callback function) once for each array element.
Note that the function takes 3 arguments:
• The item value
• The item index
• The array itself
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array.forEach()</h2>
<p>Calls a function once for each array element.</p>
<p id="demo"></p>
<script>
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
document.getElementById("demo").innerHTML = txt;
function myFunction(value) {
txt += value + "<br>";
}
</script>
</body>
</html>
The While Loop
The while loop loops through a block of code as long as a specified condition is true.
Syntax
while (condition) {
// code block to be executed
}
<!DOCTYPE html>
<html>
<body>
<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>
</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>

<h2>JavaScript Arrow Function</h2>

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

<h2>JavaScript Arrow Function</h2>

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

hello = () => "Hello World!";

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>

<h2>JavaScript Arrow Function</h2>

<p>This example shows an Arrow Function with a parameter.</p>

<p id="demo"></p>

<script>
var hello;

hello = (val) => "Hello " + val;

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>

<h2>JavaScript Arrow Function</h2>

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

hello = val => "Hello " + val;

document.getElementById("demo").innerHTML = hello("Universe!");
</script>

</body>
</html>
Setting CSS Styles using JavaScript
CSS Styles
Classes and Inheritance

Classes and Inheritance


DOM manipulation
HTML DOM Methods

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

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).
The following example changes the content (the innerHTML) of the <p> element
with id="demo":

<!DOCTYPE html>
<html>
<body>

<h2>My First Page</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>

</body>
</html>

In the example above, getElementById is a method, while innerHTML is a property.


The getElementById Method

• 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 innerHTML Property

• 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

• Iterators and Generators bring the concept of


iteration directly into the core language and
provide a mechanism for customizing the
behavior of for...of loops.
Iterators
• It’s an object or pattern that allows us to traverse over a list or
collection.
• Iterators define the sequences and implement the iterator
protocol that returns an object by using a next() method that
contains the value and done.
• The value contains the next value of iterator sequence
• The done is the boolean value true or false
• if the last value of the sequence has been consumed then it’s
true else false.
• We can check its prototype and can see if it is having a
method Symbol(Symbol.iterator) or not.
• In Array.prototype you will find Symbol(Symbol.iterator): ƒ values()
method.
• Array is by default iterable.
• Also, String, Map & Set are built-in iterables because their prototype
objects all have a Symbol.iterator() method.
<script>

const array = ['a', 'b', 'c'];

const it = array[Symbol.iterator]();

// and on this iterator method we have ‘next’ method

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;
}

// Calling the Generate Function


var gen = fun();
document.write(gen.next().value);
document.write("<br>");
document.write(gen.next().value);
document.write("<br>");
document.write(gen.next().value);
</script>
example of how to manually return from a generator
<script>

var array = ['a', 'b', 'c'];


function* generator(arr) {
let i = 0;
while (i < arr.length) {
yield arr[i++]
}
}

const it = generator(array);

// we can do it.return() to finish the generator

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

const arr = ['a', 'b', 'c'];

function* generator() {
Output
yield 1;
yield* arr;
1abc2
yield 2;
}

for (let value of generator()) {


document.write(value);
document.write("<br>");
}

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

A Promise has four states:


• fulfilled: Action related to the promise succeeded
• rejected: Action related to the promise failed
• pending: Promise is still pending i.e. not fulfilled or rejected
yet
• settled: Promise has fulfilled or rejected
A promise can be created using Promise constructor.

Syntax

var promise = new Promise(function(resolve, reject){


//do something
});

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

You might also like