KEMBAR78
Javascript Fundamentalss Org | PDF | Data Type | Java Script
0% found this document useful (0 votes)
31 views68 pages

Javascript Fundamentalss Org

The document is a teacher's guide for a JavaScript module (SWDJF301) aimed at software development students, covering both fundamental and advanced programming concepts. It outlines learning outcomes, objectives, and key topics such as integration with HTML, data manipulation, and the use of JavaScript libraries and frameworks. The guide emphasizes JavaScript's versatility in web development, server applications, and various other domains, while also providing installation instructions for development tools like Visual Studio Code.

Uploaded by

kigalibooklovers
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views68 pages

Javascript Fundamentalss Org

The document is a teacher's guide for a JavaScript module (SWDJF301) aimed at software development students, covering both fundamental and advanced programming concepts. It outlines learning outcomes, objectives, and key topics such as integration with HTML, data manipulation, and the use of JavaScript libraries and frameworks. The guide emphasizes JavaScript's versatility in web development, server applications, and various other domains, while also providing installation instructions for development tools like Visual Studio Code.

Uploaded by

kigalibooklovers
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

RQF LEVEL 3

TRADE: SOFTWARE
DEVELOPMENT

MODULE CODE: SWDJF301

TEACHER’S GUIDE
MODULE NAME: JAVASCRIPT
FUNDAMENTALS 1
MODULE NAME: APPLY JAVASCRIPT

2022
Acronyms

JS: JavaScript
AJAX: Asynchronous JavaScript and XML
Introduction
This JavaScript module covers all the fundamental and advanced
programming concepts. We have designed this JavaScript handout for
students. JavaScript is among the most powerful and widely used
programming languages for the web. It is an open-source and interpreted
programming language supported by all browsers. JavaScript is a lightweight,
interpreted programming language. It is designed for creating network-centric
applications. It is complimentary to and integrated with Java. JavaScript is
very easy to implement because it is integrated with HTML. It is open and
cross-platform.

2
Module Code and Title: SWDJF301: JAVASCRIPT FUNDAMENTALS

Learning Outcome 1: Apply JavaScript Basic Concepts


Learning Outcome 2: Manipulate data with JavaScript
Learning Outcome 3: Manipulate data with JavaScript

Learning outcome 1: Apply JavaScript Basic Concepts

Picture/s reflecting the Learning outcome 1

Learning outcome 1. Apply JavaScript Basic Concepts

Indicative contents (headings of indicative content from the module


of the curriculum)
1.1. Introduction to JavaScript
1.2. Integration of JavaScript to HTML
1.3. Use of variables in JAVASCRIPT
1.4. use of data types in JAVASCRIPT
1.5. Use of operators in JavaScript

1
Objectives apply JavaScript Basic Concepts
By the end of the learning outcome, the trainees will be able to:
1. Integrate properly JavaScript in HTML based on project structure
2. Use correctly Variables based on task
3. use correctly the Datatype based on variables
4. Use correctly the Operators based on task

1.1. Introduction to Javascript

 Definition of JAVASCRIPT
JavaScript is a lightweight, interpreted programming language. It
is designed for creating network-centric applications. It is
complimentary to and integrated with Java. JavaScript is very easy
to implement because it is integrated with HTML. It is open and
cross-platform.
JavaScript is among the most powerful and widely used
programming languages for the web. It is an open-source and
interpreted programming language supported by all browsers.
JavaScript was first known as LiveScript, but Netscape changed its name to
JavaScript, possibly because of the excitement being generated by Java.
JavaScript made its first appearance in Netscape 2.0 in 1995 with the name
LiveScript. The general-purpose core of the language has been embedded in
Netscape, Internet Explorer, and other web browsers.

✔ Application of Javascript
As mentioned before, Javascript is one of the most widely used programming
languages (Front-end as well as Back-end). It has it is presence in almost
every area of software development. I am going to list few of them here:
Client side validation - This is really important to verify any user
input before submitting it to the server and Javascript plays an
important role in validating those inputs at front-end itself.
Manipulating HTML Pages - Javascript helps in manipulating HTML
page on the fly. This helps in adding and deleting any HTML tag very
easily using javascript and modify your HTML to change its look and
feel based on different devices and requirements.

2
User Notifications - You can use Javascript to raise dynamic pop-
ups on the webpages to give different types of notifications to your
website visitors.
Back-end Data Loading - Javascript provides Ajax library, which
helps in loading back-end data while you are doing some other
processing. This really gives an amazing experience to your website
visitors.
Presentations - JavaScript also provides the facility of creating
presentations, which gives website look and feel. JavaScript provides
RevealJS and BespokeJS libraries to build web-based slide
presentations.
Server Applications - Node JS is built on Chrome's Javascript
runtime for building fast and scalable network applications. This is
an event-based library, which helps in developing very sophisticated
server applications including Web Servers.

Server Applications

JavaScript is also used to write server-side software through Node.js


open-source runtime environment. Developers can write, test and
debug code for fast and scalable network applications.

Web Servers

Node.js allows developers to use JavaScript to create a web server.

Games

Creating games on the web is another important one among applications of


JavaScript. The combination of JavaScript and HTML5 plays a major role in
games development using JS. The EaselJS library provides rich graphics for
games.

Art

A recent feature of HTML5 in JavaScript is the canvas element, which allows


drawing 2D and 3D graphics easily on a web page.

Smartwatch Apps

Pebble.js is a JavaScript framework by Pebble, allowing developers to create


applications for Pebble watches using JavaScript. Create a smartwatch app
with simple JavaScript code.

3
Mobile Apps

One of the most powerful applications of JavaScript is to create apps for


non-web contexts, meaning for things, not on the Internet. With the use of
mobile devices at an all-time high, JavaScript frameworks have been
designed to facilitate mobile app development across various platforms like
IOS, Android, and Windows. React Native framework allows cross-platform
mobile app building, where developers can use a universal front end for
Android and IOS platforms.

Flying Robots

Last but not least, you can use JavaScript to program a flying robot. With
the Node.js ecosystem, users can control numerous small robots, creative
maker projects, and IoT devices. Step into the exciting world of drones,
flying robots, and quadcopters with JavaScript.

This list goes on, there are various areas where millions of software developers
are happily using Javascript to develop great websites and others softwares.
 Install VS Code & node
Visual Studio Code is a lightweight but powerful source code editor, which
runs on your desktop and is available for Windows, macOS and Linux. It
comes with built-in support for JavaScript, TypeScript and Node.js and has a
rich ecosystem of extensions for other languages and runtimes (such as C++,
C#, Java, Python, PHP, Go, .NET).
Installation
1. Download the Visual Studio Code installer for Windows.
2. Once it is downloaded, run the installer (VSCodeUserSetup-
{version}.exe). This will only take a minute.
3. By default, VS Code is installed
under C:\Users\{Username}\AppData\Local\Programs\Microsoft VS
Code.
Alternatively, you can also download a Zip archive, extract it and run Code
from there.
Intelligent Code Completion

4
 JAVASCRIPT key concepts
Variable: A variable is simply a container, which contains some
values.
Data Types: in programming, is a classification that specifies which
type of value a variable has and what type of mathematical,
relational or logical operations can be applied to it without causing
an error. A string, for example, is a data type that is used to classify
text and an integer is a data type used to classify whole numbers.

Operators: In JavaScript, words and symbols in expressions that


perform operations certain values to arrive at another value are
known as operators.
Expressions
JavaScript's expression is a valid set of literals, variables, operators, and
expressions that evaluate to a single value
Keywords
In JavaScript, keywords are reserved words that have a specific purpose and are already
defined in the language.
A list of all the reserved words in JavaScript are given in the following table. They cannot be
used as JavaScript variables, functions, methods, loop labels, or any object names.

abstract Else instanceof switch

boolean Enum int synchronized

break Export interface this

byte extends long throw

case False native throws

catch Final new transient

char Finally null true

5
class Float package try

const For private typeof

continue function protected var

debugger Goto public void

default If return volatile

delete implements short while

do Import static with

double In super

Comments: The JavaScript comments are meaningful way to


deliver message. It is used to add information about the code,
warnings or suggestions so that end user can easily interpret the
code.
JavaScript comments can be used to explain JavaScript code, and to make it more
readable.

Single Line Comments

Single line comments start with //.

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

This example uses a single-line comment before each code line:

Example

// Change heading:
document.getElementById("myH").innerHTML = "My First Page";

// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";

Multi-line Comments

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

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

6
This example uses a multi-line comment (a comment block) to explain the code:

Example

/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";

Javascript libraries is a file that contains a set of prewritten


functions or codes that you can repeatedly use while executing
JavaScript tasks.

● React Javascript
React (also known as React.js or ReactJS) is a free and open-source
front-end JavaScript library for building user interfaces based on UI
components.
● JQuery
It's a library of JavaScript functions that make it easy for webpage
developers to do common tasks-- like manipulating the webpage, responding
to user events, getting data from their servers, building effects and
animations, and much more.
● Three Javascript
Three.js is a cross-browser JavaScript library and application programming interface
(API) used to create and display animated 3D computer graphics in a web.

A JavaScript framework is a set of JavaScript code libraries that provide pre-written


code for everyday programming tasks to a web developer.

 Vue Javascript

Vue.js is an open-source progressive JavaScript framework used to develop interactive


web user interfaces and single-page applications (SPAs).

 Angular Javascript

7
AngularJS is a client side JavaScript MVC framework to develop a dynamic web
application.

 Express Javascript

Express is a minimal and flexible Node.js web application framework that provides a
robust set of features for web and mobile applications.

A JavaScript engine is a software component that executes JavaScript


code.
● Node Javascript
● v8 Engine
 JavaScript versions
JavaScript was first known as Live Script, but Netscape changed its name
to JavaScript, possibly because of the excitement being generated by Java.
JavaScript made its first appearance in Netscape 2.0 in 1995 with the
name Live Script. The general-purpose core of the language has been
embedded in Netscape, Internet Explorer, and other web browsers.

The ECMA-262 Specification defined a standard version of the core


JavaScript language.

JavaScript is a lightweight, interpreted programming language.


Designed for creating network-centric applications.
Complementary to and integrated with Java.
Complementary to and integrated with HTML.
Open and cross-platform

1.2. Integration of JavaScript to HTML


JavaScript, also abbreviated to JS, is a programming language used in web
development. As one of the core technologies of the web alongside HTML and
CSS, JavaScript is used to make webpages interactive and to build web apps.
Modern web browsers, which adhere to common display standards, support
JavaScript through built-in engines without the need for additional plugins.
When working with files for the web, JavaScript needs to be loaded and run
alongside HTML markup. This can be done either inline within an HTML
document or in a separate file that the browser will download alongside the
HTML document.
 Referencing HTML to JavaScript

8
Execution of JavaScript can be done by placing JavaScript statements
within the HTML tags in a web page. JavaScript is an easy language when it
comes to coding.
Generally there are three places where you can put the JavaScript code:
 Inside Body Tag
 Inside head
 External JavaScript file
Here is an example to understand this from an initial level:
<script type="text/javascript">
document.write("PHPTPOINT is the place to study javascript easily");
</script>
Using the script tag signifies that we are using JavaScript
3 Places to put JavaScript code
1. Between the body tag of html
2. Between the head tag of html
3. In .js file (external javaScript)

9
JavaScript Syntax: Code between the Body Tags
In the above-explained example, there is a depiction of the dynamic content
using the JavaScript. Here is another example displaying alert box.
<html>
<head>
<title>JavaScript Inside Body</title>
</head>
<body>
<script type="text/javascript">
function msg()
{
alert("Hello phptpoint");
}
</script>
</body>
</html>

JavaScript Syntax: Code between the head tag


We have seen the example of alert code inside the body tag, now let us see
the example of JavaScript alert OR displaying result inside the head tag.
In order to create a function in JavaScript, the function must be written
with function_ name as shown in the example below.

An event is needed to call a function. In the following example on click even


is used to call msg () function.

<html>
<head>
<script type="text/javascript">
function msg()
{
alert("Hello phptpoint");
}
</script>
</head>
<body>
<p>Welcome to phptpoint</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>

10
Using External JavaScript

With JavaScript, a external JavaScript file can be created and can easily be
embedded into many HTML pages. Since a single JavaScript file can be used
in various HTML pages hence, it provides code re usability.
In order to save a JavaScript file, .js extension must be used. To increase
the speed of the webpages, it is recommended to embed the entire
JavaScript file in to a single file.

Advantages of External JavaScript:

 Cached JavaScript files can speed up page loading


 It makes JavaScript and HTML easier to read and maintain
 It separates the HTML and JavaScript code
 It focuses on code re usability that is one JavaScript Code can run in
various HTML files.

Here is a simple example:


function msg()
{
alert("Hello phptpoint");
}
The above file will be saved with the name myscript.js

Here is another example that includes the External JavaScript in to HTML


page. This code calls the JavaScript function on button click.

1. <html>

<head>
<title>External Javascript Example-Phptpoint</title>
<script type="text/javascript" src="myscript.js"></script>
</head>
<body>
<p>Welcome to Phptpoint</p>
<input type="button" value="click" onclick="msg()"/>
</body>
</html>

Example:
<!DOCTYPE html>

11
<html>
<center>
<body>
<h2>External JavaScript</h2>
<p id="demo">Geeks For Geeks.</p>
<button type="button" onclick="myFunction()">Try
it</button>
<script src="myScript.js"></script>
</body>
<center>
</html>

Using external Javascript reference (CDN)


What is a CDN?
A CDN is a Content Delivery Network. These are file hosting services for
multiple versions of common libraries. They are usually highly performant
and offer location cached files so no matter where your users are, they
receive the files from geo locations close to them. This can make your
application faster than hosting files yourself.
Example:

<script src=
"https://unpkg.com/ag-grid-community/dist/ag-grid-community.min.nostyle.js">
</script>

JavaScript output
JavaScript Display Possibilities. JavaScript can "display" data in different
ways:

 Writing into an HTML element, using innerHTML.


 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().
 Writing into the browser console, using console.log ().

Using innerHTML

To access an HTML element, JavaScript can use


the document.getElementById(id) method. The id attribute defines the HTML
element. The innerHTML property defines the HTML content:

Example
<Html>
<Head>

12
<Body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>

Using document.write()
For testing purposes, it is convenient to use document.write():
Example: 1
<! DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph. </p>
<script>
document.write(5 + 6);
</script>
</body>
</html>

Example: 2

<! DOCTYPE html>


<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<button type="button" onclick="document.write(5 + 6)">Try it</button>

</body>
</html>

Using window.alert()
You can use an alert box to display data:

<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>

13
<script>
alert(5 + 6);
</script>
</body>
</html>

Using console.log ()
For debugging purposes, you can call the console.log() method in the
browser to display data.
Example

<! DOCTYPE html>


<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>

JavaScript Print
JavaScript does not have any print object or print methods. You cannot
access output devices from JavaScript. The only exception is that you can
call the window.print() method in the browser to print the content of the
current window.

<!DOCTYPE html>
<html>
<body>
<button onclick="window.print()">Print this page</button>
</body>
</html>

1.3. Use of variables in JAVASCRIPT


JavaScript Variable
1. JavaScript variable
2. JavaScript Local variable
3. JavaScript Global variable

14
A JavaScript variable is simply a name of storage location. There are two
types of variables in JavaScript : local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as
identifiers).
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or
dollar( $ ) sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are
different variables.
JavaScript variables

1. var x = 10;
2. var _value="sonoo";
Example of JavaScript variable
Let us see a simple example of JavaScript variable.

1. <script>
2. var x = 10;
3. var y = 20;
4. var z=x+y;
5. document.write(z);
6. </script>

Output of the above example

30
JavaScript local variable

A JavaScript local variable is declared inside block or function. It is accessible


within the function or block only. For example:

1. <script>
2. function abc(){
3. var x=10;//local variable
4. }
5. </script>

Or,

1. <script>
2. If(10<13){

15
3. var y=20;//JavaScript local variable
4. }
5. </script>

JavaScript global variable

A JavaScript global variable is accessible from any function. A variable i.e.


declared outside the function or declared with window object is known as
global variable. For example:

1. <script>
2. var data=200;//gloabal variable
3. function a(){
4. document.writeln(data);
5. }
6. function b(){
7. document.writeln(data);
8. }
9. a();//calling JavaScript function
10. b();
11. </script>
1.4 Use of data types in JAVASCRIPT
To hold different types of values, JavaScript provides different data types.
In JavaScript, there are only two types of data types:

 Primitive data type


 Non-primitive (reference) data type
JavaScript is generally known as a dynamic type language that means
there is no need to specify the type of variable as it is dynamically used by
the JavaScript engine. In order to specify the data we have to
use var keyword. This can hold any type of values e.g. strings, number and
more.

1. Primitive data types in JavaScript


In JavaScript, there are five types of primitive data types as depicted below:

Data Type Description


String This represents the sequence of characters e.g. "hi"
Number This represents the numeric values e.g. 130
Boolean This represents the boolean value whether it is either false or true
Undefined This represents the undefined value
Null This represents the null i.e. no value present.
Example:

16
<script>
var x=20;//holding number
var y="Phptpoint";//holding string
var bool=true;//holding boolean true
var bools=false;//holding boolean false
var blank=null;//holding null value
<script>
2. Non-Primitive Data Types in JavaScript
There are generally three types of non-primitive data types which are as
follows:

Data Type Description


Object This data type represents the instance through which the members can be accessed.
Array This represents a group of similar values
RegExp This represents a regular expression
Example of Object:

<script>
//example of Object
stu={id:101,name:"sanjeev"}
alert(stu.id+" "+stu.name);
</script>
Example of Array:

<script>
//example of Array
arr=Array(101,"sanjeev");
alert(arr[0]+" "+arr[1]);
</script>

3. Type-casting
Typecasting in JavaScript means converting one data type to another data
type i.e., the conversion of a string data type to Boolean or the conversion of
an integer data type to string data type. The typecasting in JavaScript is also
known as type conversion or type coercion.
Types of conversions
The type casting is of two types in JavaScript. They are the implicit type
conversions and the explicit type conversions.
Typecasting in JavaScript means converting one data type to another data type.

17
 Converting Strings to Numbers
 Converting Numbers to Strings
 Converting Dates to Numbers
 Converting Numbers to Dates
 Converting Booleans to Numbers
 Converting Numbers to Booleans

JavaScript Type Conversion

JavaScript variables can be converted to a new variable and another data


type:

 By the use of a JavaScript function


 Automatically by JavaScript itself

Converting Strings to Numbers

The global method Number() converts a variable (or a value) into a number.
A numeric string (like "3.14") converts to a number (like 3.14).
An empty string (like "") converts to 0.
A non numeric string (like "John") converts to NaN (Not a Number).

Examples

These will convert:

Number("3.14")
Number(Math.PI)
Number(" ")
Number("")

These will not convert:

Number("99 88")
Number("John")
Number Methods

In the chapter Number Methods, you will find more methods that can be
used to convert strings to numbers:

Method Description

18
Number() Returns a number, converted from its argument

parseFloat() Parses a string and returns a floating point number

parseInt() Parses a string and returns an integer

The Unary + Operator

The unary + operator can be used to convert a variable to a number:

Example

let y = "5"; // y is a string


let x = + y; // x is a number

If the variable cannot be converted, it will still become a number, but with
the value NaN (Not a Number):

Example

let y = "John"; // y is a string


let x = + y; // x is a number (NaN)

Converting Numbers to Strings

The global method String() can convert numbers to strings.

It can be used on any type of numbers, literals, variables, or expressions:

Example

String(x) // returns a string from a number variable x


String(123) // returns a string from a number literal 123
String(100 + 23) // returns a string from a number from an expression

The Number method toString() does the same.

19
Example

x.toString()
(123).toString()
(100 + 23).toString()

More Methods

In the chapter Number Methods, you will find more methods that can be
used to convert numbers to strings:

Method Description

toExponential() Returns a string, with a number rounded and written using


exponential notation.

toFixed() Returns a string, with a number rounded and written with a specified
number of decimals.

toPrecision() Returns a string, with a number written with a specified length

Converting Dates to Numbers

The global method Number() can be used to convert dates to numbers.

d = new Date();
Number(d) // returns 1404568027739

The date method getTime() does the same.

d = new Date();
d.getTime() // returns 1404568027739

20
Converting Dates to Strings

The global method String() can convert dates to strings.

String(Date()) // returns "Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)"

The Date method toString() does the same.

Example

Date().toString() // returns "Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight
Time)"

In the chapter Date Methods, you will find more methods that can be used
to convert dates to strings:

Method Description

getDate() Get the day as a number (1-31)

getDay() Get the weekday a number (0-6)

getFullYear() Get the four digit year (yyyy)

getHours() Get the hour (0-23)

getMilliseconds() Get the milliseconds (0-999)

getMinutes() Get the minutes (0-59)

21
getMonth() Get the month (0-11)

getSeconds() Get the seconds (0-59)

getTime() Get the time (milliseconds since January 1, 1970)

Converting Booleans to Numbers

The global method Number() can also convert booleans to numbers.

Number(false) // returns 0
Number(true) // returns 1

Converting Booleans to Strings

The global method String() can convert booleans to strings.

String(false) // returns "false"


String(true) // returns "true"

The Boolean method toString() does the same.

false.toString() // returns "false"


true.toString() // returns "true"

Automatic Type Conversion

When JavaScript tries to operate on a "wrong" data type, it will try to convert
the value to a "right" type.

The result is not always what you expect:

22
5 + null // returns 5 because null is converted to 0
"5" + null // returns "5null" because null is converted to "null"
"5" + 2 // returns "52" because 2 is converted to "2"
"5" - 2 // returns 3 because "5" is converted to 5
"5" * "2" // returns 10 because "5" and "2" are converted to 5 and 2

Automatic String Conversion

JavaScript automatically calls the variable's toString() function when you try
to "output" an object or a variable:

document.getElementById("demo").innerHTML = myVar;

// if myVar = {name:"Fjohn"} // toString converts to "[object Object]"


// if myVar = [1,2,3,4] // toString converts to "1,2,3,4"
// if myVar = new Date() // toString converts to "Fri Jul 18 2014 09:08:55 GMT+0200"

Implicit type casting

The implicit type casting is the conversion of data type done due to the
internal requirement or automatic conversion by the compiler or the
interpreter. To understand the implicit conversion let us consider the
example of the boolean values (primitive). JavaScript expects a boolean
value in a conditional expression. So JavaScript will temporarily convert the
value in parentheses to a Boolean to evaluate the if expression

val = 1;
if (val) {
console.log( 'yes, val exists' );
}

Implicit conversion with == operator


Type conversion is also performed when comparing values using the equal
(==) and not equal (!=) operators. So when you compare the number 125 with
a string '125' using the equals (==) operator, the expression evaluates to true

console.log( 125 == '125' );

23
1.4. Use of operators in Javascript
In JavaScript, words and symbols in expressions that perform operations
certain values to arrive at another value are known as operators. Any value
on which an operator performs some action is called an operand. An
expression may contain one operand and one operator (called a unary
operator) or two operands separated by one operator (called a binary
operator). Many of the same symbols are used in a variety of operators. The
combination and order of those operator symbols are what distinguish their
powers. In simple words, an operator is the one operating the operand.
There are many use of operators in JavaScript such as comparing values,
performing arithmetic operations, etc.

These are some of the JavaScript operators:


 Arithmetic operators
 Comparison operators
 Bitwise Operators
 Logical Operators
 Assignment Operators
 Ternary Operators
Arithmetic Operators:
 These operators are used to operate mathematical
operations between numeric operands.

Operator Description

+ Used to add two numeric operands.

- Used to subtract right operand from left operand

* Used to multiply two numeric operands.

/ Used to divide left operand by right operand.

% Modulus operator. It returns remainder of two operands.

++ Increment operator. It Increases operand value by one.

-- Decrement operator. It decreases value by one.

 The following example will help you in understand the Arithmetic


Operators in running different tasks on Javascript operators:

24
 var a = 2, b = 4;
 a + b; //returns 6
 b - a; //returns 2
 a * b; //returns 8
 b / a; //returns 2
 a % 2; //returns 1
 a++; //returns 3
 a--; //returns 1

Note : + Operator executes a series of operations provided that one of the


operands is of string type. This example will help you understand the
working of + Operator on operands of various data types.

var w = 5, x = "Hello ", y = "World!", z = 10;


w + x; // "5Hello "
x + y; // "Hello World!"
w + z; // 15

Comparison Operators
Any time you compare two values in JavaScript, the result is a Boolean true
or false value.
You have a wide selection of comparison operators to choose from,
depending on the kind of test you want to apply to the two operands.
There are basically 4 ways by which the equality is tested that are listed as
follows:

 '==' operator
 '===' operator
 SameValuezero: this is mainly used in maps, arrays and sets.
 SameValue: these are used elsewhere.
All the various types of comparison operators are mentioned in the table
below:

Operator Description Example


== Is equal to 11==22 = false
=== Identical (equal and of same type) 11==22 = false
!= Not equal to 10!=20 = true
!== Not Identical 22!==22 = false
> Greater than 22>12 = true
>= Greater than or equal to 22>=12 = true

25
< Less than 22<12 = false
<= Less than or equal to 22<=12 = false
'==' operator:
In javascript, the use of this operator is mainly in comparing two value on
both the sides and then return true or false as a result. This javascript
operator, evaluates the equality only after converting or we can say bringing
both the values to a common type known as type coercion.

For numeric values, the results are the same as those you would expect
from your high school algebra class.

10 == 10 // true
10 == 10.0 // true
9 != 10 // true
9 > 10 // false
9.99 <= 9.98 // false
'===' operator:
This JavaScript operator is also called as strict equality operator, it
simultaneously compares the value and the type.

JavaScript Bitwise Operators

The bitwise operator’s carryout bitwise operations on the operands. Here are
the bitwise operators:

Operator Description Example


& Bitwise AND (10==20 & 20==33) = false
| Bitwise OR (10==20 | 20==33) = false
^ Bitwise XOR (10==20 ^ 20==33) = false
~ Bitwise NOT (~10) = -10
<< Bitwise Left Shift (10<<2) = 40
>> Bitwise Right Shift (10>>2) = 2
>>> Bitwise Right Shift with Zero (10>>>2) = 2

JavaScript Logical Operators


All the various types of Logical operators are mentioned in the table below:

Symbol Description Example

&& Logical AND (12==22 && 22==33) = false

|| Logical OR (12==22 || 22==33) = false

26
! Logical Not !(12==22) = true

JavaScript Assignment Operators


All the various types of Assignment operators are mentioned in the table
below:

Symbol Description Example


= Assign 10+10 = 20
+= Add and Assign var a=10; a+=20; Now a = 30
-= Subtract and assign var a=20; a-=10; Now a = 10
*= Multiply and assign var a=10; a*=20; Now a = 200
/= Divide and assign var a=10; a/=2; Now a = 5
%= Modulus and assign var a=10; a%=2; Now a = 0

Ternary (Special) Operators


Symbol Description
(?:) Conditional Operator returns value based on the condition. It is like if-
else.

JavaScript also contains a conditional operator that assigns a value to a


variable based on some condition.

Syntax

variablename = (condition) ? value1:value2

Example

let voteable = (age < 18) ? "Too young":"Old enough";

If the variable age is a value below 18, the value of the variable voteable
will be "Too young", otherwise the value of voteable will be "Old enough".

The ?? operator returns the first argument if it is null or undefined.


Otherwise it returns the second.

27
Example

let name = null;


let text = "missing";
let result = name ?? text;

The nullish operator is supported in all browsers since March 2020:

The ?. operator returns undefined if an object is undefined or null (instead of


throwing an error).

Example

// Create an object:
const car = {type:"Fiat", model:"500", color:"white"};
// Ask for car name:
document.getElementById("demo").innerHTML = car?.name;

Learning outcome 2: MANIPULATE DATA WITH JAVASCRIPT

Picture/s reflecting the Learning outcome 2

Learning outcome 2. Manipulate data with JavaScript

28
Indicative contents (headings of indicative content from the module
of the curriculum)
2.1. Conditional statements are properly implemented according to the
control flow
1.2. Loop functions are appropriately used based on task
1.3. Functions are appropriately used based on the task
1.4. Object are correctly defined based on task
1.5. Arrays are appropriately applied based on task

Duration: ……….hrs

Objectives apply JavaScript Basic Concepts


By the end of the learning outcome, the trainees will be able to:
1. Integrate properly JavaScript in HTML based on project structure
2. Use correctly Variables based on task
3. use correctly the Datatype based on variables
4. Use correctly the Operators based on task

2.1 JavaScript conditional statements


While writing a program, there may be a situation when you need to adopt
one out of a given set of paths. In such cases, you need to use conditional
statements that allow your program to make correct decisions and perform
right actions.

JavaScript If-else

The JavaScript if-else statement is used to execute the code whether


condition is true or false. There are three forms of if statement in JavaScript.
1. If Statement
2. If else statement
3. if else if statement
1. JavaScript If statement
It evaluates the content only if expression is true. The signature of
JavaScript if statement is given below.
Syntax:
if(expression){
//content to be evaluated

29
}
Here is an example of If statement in JavaScript:
Example
<script>
var x=22;
if(x>11)
{
document.write("value of x is bigger than 11");
}
</script>

Output: value of x is bigger than 11.


2. If-else statement in JavaScript
If-else statement computes the content whether the condition is true or
false. It means if condition is true then print some statement otherwise print
some different statement.
Here is the syntax of if-else statement:
<script>
if(expression)
{
//content that is to be evaluated if condition is true
}
else
{
//content that is to be evaluated if condition is false
}
</script>
Here is an example of the if-else statement to find out the whether the
number is even or odd:
Example
<script>
var x=10;
if(x%2==0)
{
document.write("x is even number");
}
else
{
document.write("x is odd number");
}
</script>

Output: x is even number

30
3. If-else-if statement in JavaScript
If-else-if statement computes the content only if expression is true from
various.
When we want to use condtion more than one times then we can use Nested
if-else.
syntax :

<script>
if(expression1)
{
//content that is to be evaluated if expression1 is true
}
else if(expression2)
{
//content that is to be evaluated if expression2 is true
}
else if(expression3)
{
//content that is to be evaluated if expression3 is true
}
else
{
//content that is to be evaluated if no expression is true
}
</script>
Here is an example of else-if-else statement in JavaScript;
Example 1
<script>
var x=10;
if(x==5){
document.write("x is equal to 5");
}
else if(x==10){
document.write("x is equal to 10");
}
else if(x==15){
document.write("x is equal to 15");
}
else{
document.write("x is not equal to 5, 10 or 15");
}
</script>

Output: x is equal to 10
JavaScript Switch
In order to execute one code from multiple expressions, JavaScript Switch is
used. It is known to be very similar to the if-else statement and due to the
31
permitted use of numbers and characters it is more convenient than if-else-
if.

Here is the signature of JavaScript Switch Statement:

switch(expression)
{
case value1:
code that is to be executed;
break;
case value2:
code that is to be executed;
break;
.
.
.
.
default:
code that is to be executed if above values are not matched;
}
Example 1

<script>
var Class='B';
var result;

switch(Class)
{
case 'A':
result="A Class";
break;
case 'B':
result="B Class";
break;
case 'C':
result="C Class";
break;
default:
result="No class";
}
document.write(result);
</script>
Output: The output for the above-mentioned example is B Class.

Example 2(without using Break)

32
<script>
var Class='B';
var result;
switch(Class)
{
case 'A':
result=" A Class";
case 'B':
result=" B Class";
case 'C':
result=" C Class";
default:
result=" No Class";
}
document.write(result);
</script>
Output: No Class

JavaScript Loop
In order to iterate the piece of code using the for, while, do-while, or for-in
loops JavaScript is used. It is generally used in array and helps in making
the code compact.
In JavaScript, there are generally four types of loops:
1. for loop
2. while loop
3. do-while loop
4. for-in loop
1.For Loop in JavaScript
The For Loop in JavaScript iterates the elements for a finite number of times
and should be used when the number of iteration is known.
Here is the syntax mentioned below:
JavaScript Loop
In order to iterate the piece of code using the for, while, do-while, or for-in
loops JavaScript is used. It is generally used in array and helps in making
the code compact.
In JavaScript, there are generally four types of loops:
1. for loop

33
2. while loop
3. do-while loop
4. for-in loop
1. For Loop in JavaScript
The For Loop in JavaScript iterates the elements for a finite number of times
and should be used when the number of iteration is known.
Here is the syntax mentioned below:

for (initialization; condition; increment/decrement)


{
code that you wants to be executed
}
Let's take an example for For loop

<script>
for (i=2; i<=6; i++)
{
document.write(i + "<br/>")
}
</script>
Here is the output for the above mentioned example:
2
3
4
5
6

Example 2(Sum of 1 to 100)

<script>
var sum=0;
for (var i=1; i<=100; i++)
{
sum=sum+i;
}
document.write("Sum of 1 to 100="+sum);
</script>

34
Here is the output for the above mentioned example: Sum of 1 to
100=5050

2.While Loop in JavaScript


While loop in JavaScript iterates the elements for the infinite times and it is
generally used if the number of iteration is unknown.

Here is the syntax of while loop:

while (condition)
{
code that you wants to be executed
}
Let's take an example for while loop

<script>
var i=10;
while(i<=12)
{
document.write(i + "<br/>");
i++;
}
</script>

The output of the above mentioned example will be as follows:


10
11
12

Example 2 (Print table of 5)

<script>
var table=5;
var i=1;
var tab=0;
while(i<=10)
{
var tab=table*i;
document.write(tab + " ");
i++;

35
}
</script>

The output of the above-mentioned example will be as follows:


5 10 15 20 25 30 35 40 45 50

3. Do-While Loop in JavaScript


Just like while loop, the do-while loop iterates the elements for an infinite
number of times. But, the code is executed at least one time despite of the
fact that condition is true or false.

Here is the syntax of do-while loop:

do
{
code that you wants to be executed
}
while (condition);
Let's take an example for Do-while loop

<script>
var i=20;
do
{
document.write(i + "<br/>");
i++;
}
while (i<=23);
</script>
Here is the output for the above-mentioned example:
20
21
22
23

4.The while Loop

The most basic loop in JavaScript is the while loop which would be discussed
in this chapter. The purpose of a while loop is to execute a statement or code
block repeatedly as long as an expression is true. Once the expression
becomes false, the loop terminates.

36
Syntax
While (expression) {
Statement(s) to be executed if expression is true
}

Example
Try the following example to implement while loop.

<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;
document.write("Starting Loop ");
while (count < 10) {
document.write("Current Count : " + count + "<br />");
count++;
}
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Output

Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!

37
Set the variable to different value and then try...

5. For-in Loop in JavaScript


The for-in loop in JavaScript is generally used to iterate the properties of an
object/Associative arrat.

Here is the syntax for for-in loop:

for (Tempvariablename in object/array)


{
statement or code to be executed
}
Let's take an example for For-in loop

<html>
<body>
<script type = "text/javascript">
var user = {fname:"sanjeev", lname:"kumar",country:"india"};
var x;
for (x in user)
{
document.write(x+": "+user[x]+"<br>");
}
</script>
</body>
</html>
Here is the output for the above mentioned example:
fname: sanjeev
lname: kumar
country: india

Example 2:

<html>
<body>
<script type = "text/javascript">
var aProperty;
document.write("Navigator Object Properties:<br/>");
for (aProperty in navigator) {
document.write(aProperty);
document.write("<br/>");
}

38
document.write ("Exiting from the loop!");
</script>
<p>Set the variable to different object and then try...<p>
</body>
</html>
Here is the output for the above mentioned example:
Navigator Object Properties:
vendorSub
productSub
vendor
maxTouchPoints
hardwareConcurrency
cookieEnabled
appCodeName
appName
appVersion
platform
product
userAgent
language
languages
onLine
doNotTrack
geolocation
mediaCapabilities
connection
plugins
mimeTypes
webkitTemporaryStorage
webkitPersistentStorage
getBattery
sendBeacon
getGamepads
javaEnabled
vibrate
userActivation
mediaSession
permissions
registerProtocolHandler
unregisterProtocolHandler
deviceMemory
clipboard
credentials
keyboard
locks
mediaDevices
serviceWorker

39
storage
presentation
bluetooth
usb
requestMediaKeySystemAccess
getUserMedia
webkitGetUserMedia
requestMIDIAccess
Exiting from the loop!

JavaScript String
The JavaScript string is an object that represents a sequence of characters.
There are 2 ways to create string in JavaScript
1. By string literal
2. By string object (using new keyword)
1) By string literal
The string literal is created using double quotes. The syntax of creating string using
string literal is given below:
1. var stringname="string value";

Let's see the simple example of creating string literal.

<script>
var str="This is string literal";
document.write(str);
</script>

Output:

This is string literal

2) By string object (using new keyword)


The syntax of creating string object using new keyword is given below:

1. var stringname=new String("string literal");

Here, new keyword is used to create instance of string. Let's see the example of
creating string in JavaScript by new keyword.

<script>
var stringname=new String("hello javascript string");

40
document.write(stringname);
</script>

Escaping special characters

To escape special characters, you use the backslash \ character. For


example:

 Windows line break: '\r\n'


 Unix line break: '\n'
 Tab: '\t'
 Backslash '\'

The following example uses the backslash character to escape the single
quote character in a string:

let str = 'I\'m a string!'

Concatenating strings via + operator

To concatenate two or more strings, you use the + operator:

let name = 'John';


let str = 'Hello ' + name;
console.log(str); // "Hello John"

JavaScript Function

Functions in JavaScript are used to execute operations. JavaScript


functions can be called multiple times in order to reuse the code.
Let's get to know the advantages of JavaScript functions:
Mainly there are 3 advantages of JavaScript functions.

 Reusability of code: A function can be called multiple times hence,


saving the code.

41
 Less amount of coding: There is no need of writing multiple lines of
code each time to execute a common task hence, it makes the
program compact.
 Debugging becomes easier: Codes are divided in to blocks hence
debugging a code becomes easier.

Syntax of JavaScript Function


The syntax for declaring a function is displayed below:

function functionName([arg1, arg2, ...argN])


{
//code to be executed
}
Please note that JavaScript functions can have zero or more arguments.

Example of JavaScript Function


Let's take an example to understand the JavaScript Function that
doesn't contain any arguments.

<html>
<head>
<title>JavaScript Function</title>
<script>
function msg()
{
alert("Welcome to PHPTPOINT");
}
</script>
</head>
<body>
<input type="button" onclick="msg()" value="Welcome"/>
</body>
</html>
Output :Output of the above mentioned example is a call button named
‘Welcome’ that displays the message ‘Welcome to PHPTPOINT whenever the
button is clicked.

Arguments In Javascript Functions

A function can be called in JavaScript by passing Arguments. Here is one


example of a JavaScript Function containing one argument.

<html>

42
<head>
<title>JavaScript Function</title>
<script>
function getcube(Integer)
{
alert(Integer* Integer * Integer);
}
</script>
</head>
<body>
<input type="button" value="get value" onclick="getcube(6)"/>
</body>
</html>
Output :The output of the above mentioned example is the clickable button
named ‘get value’ that diplays the cube of the number 6 that equals to 216.

JavaScript Function with Return Value

Here, we can use the value returned by the function and it can be used in
the program. Here is one example of a JavaScript Function that returns a
value.

<html>
<head>
<title>JavaScript Function</title>
</head>
<body>
<script>
function getInfo()
{
return "Hello PHPTPOINT! How are Things?";
}
document.write(getInfo());
</script>
</body>
</html>

Output: Output of the above example is a text displayed as “Hello


PHPTPOINT! How are Things?”

43
Object Of Javascript Function

The main motive of Function Constructor in JavaScript is creating a new


Function object that executes the code globally.

A function is created dynamically in an unsecured way, if the constructor is


called directly.

Here is the Syntax

new Function ([arg1[, arg2[, ....argn]],] functionBody)


Here are the Parameters
arg1, arg2, .... , argn – these represents the argument used by the function.
functionBody - It depicts the definition of the function.

Function Methods In Javascript

Method Description

apply() In order to call a function that contains this value and a single
array of arguments.

bind() In order to create a new function this method is used.

call() In order to call a function that contains this value and an argument
list.

toString() This returns the result in the form of a string.

Examples of JavaScript Function Object

1. Here is an example to display the sum of given numbers.

1. <script>
2. var add=new Function("num1","num2","return num1+num2");
3. document.writeln(add(5,25));
4. </script>

The output of the above mentioned example is 30.

2. Here is an example to display the power of the given value.

1. <script>

44
2. var pow=new Function("num1","num2","return
Math.pow(num1,num2)");
3. document.writeln(pow(5,3));
4. </script>

The output of the above-mentioned example is 125.

JavaScript provides a wide range of built-in methods that can be used


to perform various operations on different data types. Here are some
commonly used methods in JavaScript:

**String Methods:**

- `length`: Returns the length of a string.

- `toUpperCase()`: Converts a string to uppercase.

- `toLowerCase()`: Converts a string to lowercase.

- `trim()`: Removes whitespace from both ends of a string.

- `split()`: Splits a string into an array of substrings based on a


specified separator.

- `indexOf()`: Returns the index of the first occurrence of a specified


value in a string.

- `concat()`: Concatenates two or more strings.

**Array Methods:**

- `length`: Returns the length of an array.

- `push()`: Adds one or more elements to the end of an array and


returns the new length.

- `pop()`: Removes the last element from an array and returns that
element.

- `shift()`: Removes the first element from an array and returns that
element.

45
- `unshift()`: Adds one or more elements to the beginning of an array
and returns the new length.

- `join()`: Joins all elements of an array into a string.

- `slice()`: Returns a shallow copy of a portion of an array into a new


array.

- `forEach()`: Executes a provided function once for each array


element.

**Math Methods:**

- `random()`: Returns a random number between 0 (inclusive) and 1


(exclusive).

- `floor()`: Rounds a number down to the nearest integer.

- `ceil()`: Rounds a number up to the nearest integer.

- `round()`: Rounds a number to the nearest integer.

- `abs()`: Returns the absolute value of a number.

- `min()`: Returns the minimum value from a list of numbers.

- `max()`: Returns the maximum value from a list of numbers.

**Object Methods:**

- `keys()`: Returns an array of a given object's property names.

- `values()`: Returns an array of a given object's property values.

- `hasOwnProperty()`: Returns a boolean indicating whether the object


has a specified property.

These are just a few examples of the many methods available in


JavaScript. Each data type, such as strings, arrays, numbers, and
objects, has its own set of methods for performing operations and

46
manipulating data. You can refer to the JavaScript documentation for
a comprehensive list of methods and their usage.

In JavaScript, the `apply()`

In JavaScript, the `apply()` method is a built-in function available on


all JavaScript functions. It allows you to invoke a function with a
specified `this` value and an array (or an array-like object) of
arguments.

The syntax for using the `apply()` method is as follows:

```javascript

functionName.apply(thisValue, argumentsArray);

```

Here's a breakdown of the parameters:

- `functionName`: The name of the function you want to invoke.

- `thisValue`: The value to be used as the `this` inside the function.


This parameter is optional. If you pass `null` or `undefined`, the global
object (e.g., `window` in a browser) will be used as the `this` value.

- `argumentsArray`: An array or an array-like object containing the


arguments to be passed to the function. This parameter is also
optional. If you don't want to pass any arguments, you can either pass
`null` or an empty array (`[]`).

Here's an example to illustrate the usage of the `apply()` method:

```javascript

47
function greet(name, age) {

console.log("Hello, " + name + "! You are " + age + " years old.");

var person = {

name: "John",

age: 30,

};

greet.apply(person, ["Alice", 25]);

```

In this example, we have a function called `greet()` that takes two


parameters: `name` and `age`. We also have an object called `person`
with properties `name` and `age`. By using `apply()`, we invoke the
`greet()` function with `person` as the `this` value and an array
`["Alice", 25]` as the arguments.

The output will be: "Hello, Alice! You are 25 years old."

The `apply()` method is particularly useful when you have an array of


values that you want to pass as arguments to a function dynamically,
rather than hard-coding each argument separately. It allows you to
achieve flexibility and reusability in your code.

In JavaScript, the `bind()` method

In JavaScript, the `bind()` method is a built-in function available on all


JavaScript functions. It allows you to create a new function that,
when called, has a specified `this` value and optional arguments.

48
The `bind()` method returns a new function with the specified `this`
value and any additional arguments that are provided. It does not
invoke the original function immediately; instead, it creates a new
function that can be called later.

The syntax for using the `bind()` method is as follows:

```javascript

functionName.bind(thisValue, arg1, arg2, ...);

```

Here's a breakdown of the parameters:

- `functionName`: The name of the function you want to bind.

- `thisValue`: The value to be used as the `this` inside the function


when the bound function is called.

- `arg1, arg2, ...`: Optional arguments that are pre-set in the bound
function. These arguments will be appended to any arguments passed
to the bound function when it is called.

Here's an example to illustrate the usage of the `bind()` method:

```javascript

var module = {

x: 42,

getX: function() {

49
return this.x;

},

};

var boundGetX = module.getX.bind(module);

console.log(boundGetX()); // Output: 42

```

In this example, we have an object called `module` with a property `x`


and a method `getX`. The `getX` method returns the value of `x`. By
using `bind()`, we create a new function `boundGetX` that is bound to
the `module` object as the `this` value. When `boundGetX()` is called,
it returns the value of `x` from the `module` object.

The `bind()` method is useful when you want to create a new function
that has a specific `this` value and pre-set arguments. It allows you to
bind functions to objects or specify fixed arguments in advance, which
can be handy in situations like event handling or when you need to
pass a callback function with predefined context or arguments.

In JavaScript, a closure is a combination of a function and the lexical


environment within which that function was declared. It allows a
function to retain access to variables and parameters from its outer
(enclosing) function scope, even after the outer function has finished
executing.

Here's an example to illustrate function closure in JavaScript:

```javascript

function outerFunction() {

var outerVariable = 'I am from outerFunction';

50
function innerFunction() {

console.log(outerVariable);

return innerFunction;

var closure = outerFunction();

closure(); // Output: "I am from outerFunction"

```

In this example, the `outerFunction` defines an `outerVariable` and


declares an `innerFunction` inside it. The `innerFunction` is then
returned from `outerFunction`. When `outerFunction` is invoked and
assigned to the `closure` variable, it returns the `innerFunction`
reference.

Even though `outerFunction` has finished executing and its local


variables are technically out of scope, the `innerFunction` still retains
access to the `outerVariable` due to the closure. When we call
`closure()`, it prints the value of `outerVariable` from the outer
function's scope.

Closures are powerful because they enable functions to maintain


access to variables that were present at the time of their creation, even
if those variables are no longer in scope. This allows for more flexible
and modular code, as functions can be defined with encapsulated
state and behavior.

51
Closures are commonly used in scenarios like creating private
variables, implementing function factories, and handling
asynchronous operations where functions need access to variables
that persist across multiple callback invocations.

It's important to be mindful of closures and their memory


implications. If closures are not managed properly, they can lead to
memory leaks, as the variables they reference may not be garbage-
collected.

In JavaScript, asynchronous functions are functions that allow you to


perform non-blocking operations, such as making HTTP requests,
reading/writing files, or waiting for a certain amount of time, without
blocking the execution of other code. They provide a way to handle
asynchronous operations more easily and avoid blocking the main
execution thread.

There are several ways to work with asynchronous operations in


JavaScript:

1. Callbacks: The traditional approach before the introduction of


async/await. Callback functions are passed as arguments to
asynchronous functions and get called when the operation is
completed or an error occurs. Callbacks can lead to callback hell or
pyramid of doom when dealing with multiple nested asynchronous
operations.

2. Promises: Promises were introduced in ECMAScript 2015 (ES6) to


handle asynchronous operations more cleanly. A promise represents
the result of an asynchronous operation, which can be either resolved
(successful) or rejected (error). Promises have methods like `.then()` to
handle successful results and `.catch()` to handle errors. They also
support chaining multiple asynchronous operations using `.then()`.

3. Async/await: Introduced in ECMAScript 2017 (ES8), async/await


provides a more declarative and synchronous-like way to write

52
asynchronous code. By using the `async` keyword before a function,
you can define an asynchronous function that returns a promise.
Inside the async function, you can use the `await` keyword to pause
the execution until a promise is resolved or rejected. This way, you
can write asynchronous code that looks like synchronous code,
making it easier to reason about and maintain.

Here's an example using async/await:

```javascript

function delay(ms) {

return new Promise(resolve => setTimeout(resolve, ms));

async function fetchData() {

try {

const response = await fetch('https://api.example.com/data');

const data = await response.json();

return data;

} catch (error) {

console.error('Error:', error);

throw error;

async function process() {

53
try {

console.log('Fetching data...');

await delay(2000);

const result = await fetchData();

console.log('Data:', result);

} catch (error) {

console.error('Error:', error);

process();

```

In this example, the `process()` function is an async function that uses


`await` to wait for promises to resolve before proceeding. The
`fetchData()` function uses `await` to wait for the response from an API
request. Error handling is done using `try-catch` blocks.

Async/await allows you to write asynchronous code in a more


synchronous and readable manner, making it easier to understand
and maintain.

In JavaScript, the `confirm()` function is a built-in method that displays a


dialog box with a message and two buttons: "OK" and "Cancel." It is
commonly used to get user confirmation or to prompt the user for a yes/no
response.

The `confirm()` function takes a single parameter, which is the message to


be displayed in the dialog box. Here's an example usage:

54
```javascript
var result = confirm("Are you sure you want to delete this item?");

if (result === true) {


// User clicked "OK"
// Perform the delete operation
} else {
// User clicked "Cancel" or closed the dialog
// Cancel the delete operation
}
``` Certainly! Here's an example of an async/await function in JavaScript:

```javascript
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
throw error;
}
}
```

In the example above, we have an async function called `getData()`. It uses


the `await` keyword to pause the execution until the Promise returned by
the `fetch()` function resolves. Once the Promise is resolved, the response
object is stored in the `response` variable.

55
Next, another `await` keyword is used to pause the execution until the
Promise returned by the `response.json()` method resolves. This method
converts the response body to JSON. The resulting data is stored in the
`data` variable.

If there are any errors during the process, the code inside the `catch` block
will be executed. The error is logged to the console using `console.error()`
and then re-thrown to propagate the error to the caller.

The async function `getData()` can be called in the following way:

```javascript
getData()
.then(data => {
console.log('Data:', data);
})
.catch(error => {
console.error('Error:', error);
});
```

Here, we use the `then()` method to handle the resolved value returned by
the Promise. In this case, it will log the retrieved `data` to the console.

If any error occurs during the execution of the async function, the `catch()`
method will be triggered, allowing you to handle and log the error
appropriately.

Async/await simplifies the syntax for handling asynchronous operations,


making the code more readable and resembling synchronous code.
Arrays in JavaScript are used to store multiple values in a single variable.
They are a fundamental data structure in the language and provide various
methods and properties for manipulating and working with collections of

56
data. Here are some common operations and examples related to arrays in
JavaScript:
JavaScript can be used to perform form validation on the client side,
providing immediate feedback to users and preventing the submission of
invalid data. Here's an example of how to perform form validation using
JavaScript:

HTML:
```html
<form id="myForm" onsubmit="return validateForm()">
<input type="text" id="name" placeholder="Name">
<input type="email" id="email" placeholder="Email">
<input type="password" id="password" placeholder="Password">
<button type="submit">Submit</button>
</form>
```

JavaScript:
```javascript
function validateForm() {
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;

if (name === '') {


alert('Please enter your name.');
return false;
}

if (email === '') {


alert('Please enter your email.');

57
return false;
}

if (!isValidEmail(email)) {
alert('Please enter a valid email address.');
return false;
}

if (password === '') {


alert('Please enter a password.');
return false;
}

if (password.length < 6) {
alert('Password should be at least 6 characters long.');
return false;
}

// Form is valid, proceed with submission


return true;
}

function isValidEmail(email) {
// Regular expression pattern for email validation
const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return pattern.test(email);
}
```

58
In the example above, we have a simple form with three input fields: name,
email, and password. The `validateForm()` function is triggered when the
form is submitted. It retrieves the values entered in the input fields using
`document.getElementById().value`.

The function then performs various validation checks. If any validation


condition fails, an alert message is displayed, and `return false` prevents the
form from being submitted.

The `isValidEmail()` function utilizes a regular expression pattern to validate


the email format. It checks whether the email matches the specified pattern.

If all validation checks pass, `return true` allows the form submission to
proceed.

This is a basic example, and you can customize the validation logic
according to your specific requirements. You can add more validation rules,
validate other types of fields, display validation messages in different ways,
or apply more sophisticated validation techniques using JavaScript.
1. Creating an Array:
```javascript
const fruits = ['apple', 'banana', 'orange'];
const numbers = [1, 2, 3, 4, 5];
```

2. Accessing Array Elements:


```javascript
console.log(fruits[0]); // Output: "apple"
console.log(numbers[2]); // Output: 3
```

3. Modifying Array Elements:


```javascript

59
fruits[1] = 'grape';
console.log(fruits); // Output: ['apple', 'grape', 'orange']
```

4. Array Length:
```javascript
console.log(fruits.length); // Output: 3
```

5. Adding Elements to the End of an Array:


```javascript
fruits.push('kiwi');
console.log(fruits); // Output: ['apple', 'grape', 'orange', 'kiwi']
```

6. Removing the Last Element of an Array:


```javascript
fruits.pop();
console.log(fruits); // Output: ['apple', 'grape', 'orange']
```

7. Adding Elements to the Beginning of an Array:


```javascript
fruits.unshift('mango');
console.log(fruits); // Output: ['mango', 'apple', 'grape', 'orange']
```

8. Removing the First Element of an Array:


```javascript
fruits.shift();

60
console.log(fruits); // Output: ['apple', 'grape', 'orange']
```

9. Finding the Index of an Element in an Array:


```javascript
const index = fruits.indexOf('grape');
console.log(index); // Output: 1
```

10. Slicing an Array:


```javascript
const slicedArray = fruits.slice(1, 3);
console.log(slicedArray); // Output: ['grape', 'orange']
```

11. Iterating over an Array:


```javascript
fruits.forEach(fruit => {
console.log(fruit);
});
```

These are just a few examples of what you can do with arrays in JavaScript.
Arrays have many more methods and properties, such as `splice()`,
`concat()`, `sort()`, and `map()`, which provide flexibility for handling and
manipulating array data in various ways.
The HTML5 Canvas element is a powerful feature in JavaScript that allows
you to dynamically draw graphics and create interactive visual elements on
a web page. Here's a basic example of how to apply the Canvas element in
JavaScript:

HTML:

61
```html
<canvas id="myCanvas" width="500" height="500"></canvas>
```

JavaScript:
```javascript
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// Drawing a rectangle
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 100);

// Drawing a circle
ctx.beginPath();
ctx.arc(200, 200, 50, 0, 2 * Math.PI);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.closePath();

// Drawing text
ctx.font = '24px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello, Canvas!', 250, 250);
```

In the above example, we retrieve the Canvas element using


`document.getElementById('myCanvas')` and obtain a rendering context (2D
in this case) using `getContext('2d')`. The rendering context (`ctx`) provides
various methods and properties for drawing shapes, lines, text, and more.

62
We then proceed to draw different shapes on the canvas. We start by
drawing a red rectangle using the `fillRect()` method, specifying the x and y
coordinates, as well as the width and height.

Next, we draw a blue circle using the `arc()` method. The parameters define
the x and y coordinates of the center, the radius, and the starting and
ending angles.

Finally, we draw text using the `fillText()` method. We specify the text, font
size, and position (x and y coordinates) to render it on the canvas.

These are just a few basic examples of what you can achieve with the
HTML5 Canvas element in JavaScript. You can explore more advanced
features, such as gradients, transformations, image manipulation, and
interactivity, by utilizing the various methods and properties provided by the
Canvas API.
In this example, the `confirm()` function displays a dialog box with the
message "Are you sure you want to delete this item?" The function returns a
Boolean value indicating whether the user clicked "OK" (`true`) or "Cancel"
(`false`). Based on the user's response, you can perform different actions or
make decisions in your code.

It's important to note that the `confirm()` function is a blocking function,


meaning it pauses the execution of JavaScript code until the user makes a
choice. This can affect the user experience, so it's often recommended to use
other approaches, such as modal dialogs or custom UI components, for
more control over the user interaction.
In JavaScript, `querySelector` and `querySelectorAll` are methods provided
by the Document Object Model (DOM) API to select elements from an HTML
document based on CSS selectors.

1. `querySelector`: This method returns the first element that matches a


specified CSS selector within the document or a specific element. It returns
`null` if no matching element is found. The syntax is as follows:

```javascript
element = document.querySelector(selector);

63
```

Here, `selector` is a string representing the CSS selector for the element(s)
you want to select. `element` will be assigned the first matching element.

Example usage of `querySelector`:

```javascript
// Select the first element with class "example"
var element = document.querySelector('.example');

// Select the first <p> element with class "paragraph" within an element
with ID "container"
var elementWithinContainer = document.querySelector('#container
.paragraph');
```

2. `querySelectorAll`: This method returns a NodeList (a collection of nodes)


that contains all elements that match a specified CSS selector within the
document or a specific element. If no matching elements are found, an
empty NodeList is returned. The syntax is as follows:

```javascript
elementList = document.querySelectorAll(selector);
```

The `selector` parameter is the CSS selector for the element(s) you want to
select, and `elementList` will be assigned the NodeList containing all
matching elements.

Example usage of `querySelectorAll`:

```javascript

64
// Select all elements with class "example"
var elements = document.querySelectorAll('.example');

// Select all <p> elements with class "paragraph" within an element with ID
"container"
var elementsWithinContainer = document.querySelectorAll('#container
.paragraph');
```

With `querySelector` and `querySelectorAll`, you can select elements based


on their IDs, classes, tag names, or any other CSS selector supported by the
browser. These methods provide a convenient way to manipulate and
interact with elements on a web page using JavaScript.

65

You might also like