[go: up one dir, main page]

0% found this document useful (0 votes)
10 views47 pages

Javascript Fundamentals

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

Javascript Fundamentals

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

RQF LEVEL 3

TRADE: SOFTWARE
DEVELOPMENT

MODULE CODE: SWDJF301

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

2022
Table of content

2
Acronyms

JS: JavaScript
AJAX: Asynchronous JavaScript and XML

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

4
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

1
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

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

2
4. Use correctly the Operators based on task

Resources
Equipment Tools Materials
 Vscode  Internet
 Node  Electricity
 Computer  Notepad++  Flipchart
 Projector  Sublim  Marker pen
 White board

Advance preparation:
.
.

Indicative content 1.1: Introduction to JavaScript


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

4
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

 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.
5
Operators: In JavaScript, words and symbols in expressions that
perform operations certain values to arrive at another value are
known as operators.
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 libraries

JavaScript is a file that contains a set of prewritten functions or codes


that you can repeatedly use while executing JavaScript tasks.
React JavaScript
JQuery
Three JavaScript

 JavaScript frameworks
JavaScript frameworks are a hugely important part of today is
programming community. In brief, JavaScript frameworks are a
collection of libraries containing code written in JavaScript, making life
a lot easier for software developers. Each JavaScript framework offers
pre-built codes for different areas and different purposes in software
development.
Vue JavaScript
Angular JavaScript
Express JavaScript

Difference between JavaScript Library and Framework


Now, let us look at the major differences between JavaScript library
and framework:
In short, JavaScript libraries consist of functions that applications can
call while performing a specific task. Whereas a framework stands for
how you design an application.
 JavaScript runtime environment
● 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.

6
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

Theoretical learning Activity


 ………………………………. (example: ask trainees to brainstorm
about………. within groups)
 ……………………………….
 ……………………………….

Practical learning Activity


 …………………………………… (Example: Trainees in pair perform
…………………)

Points to Remember (Take home message)

Indicative content 1.2. Integration of JavaScript to HTML

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.

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

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

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

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

10
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>
</Head>
<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()

11
You can use an alert box to display data:

<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<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>

12
Theoretical learning Activity
 ………………………………. (example: ask trainees to brainstorm
about………. within groups)
 ……………………………….
 ……………………………….

Practical learning Activity


 …………………………………… (Example: Trainees in pair perform
…………………)

Points to Remember (Take home message)

Indicative content 1.3. Use of variables in JAVASCRIPT

1.3. Use of variables in JAVASCRIPT


JavaScript Variable
1. JavaScript variable
2. JavaScript Local variable
3. JavaScript Global variable
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.

13
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){
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:

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

Theoretical learning Activity


 ………………………………. (example: ask trainees to brainstorm
about………. within groups)
 ……………………………….
 ……………………………….

Practical learning Activity


 …………………………………… (Example: Trainees in pair perform
…………………)

Points to Remember (Take home message)

Indicative content 1.3. Use of variables in JAVASCRIPT

1.4 Use of data types in JAVASCRIPT

15
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:
<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 Description
Type
Object This data type represents the instance through which the members can be
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:

16
<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.
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' );

Theoretical learning Activity


 ………………………………. (example: ask trainees to brainstorm
about………. within groups)
 ……………………………….

17
 ……………………………….

Practical learning Activity


 …………………………………… (Example: Trainees in pair perform
…………………)

Points to Remember (Take home message)

Indicative content 1.3. Use of operators in Javascript

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:
18
 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:

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

19
 '==' 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
< 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
20
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

! 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


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

21
Theoretical learning Activity
 ………………………………. (example: ask trainees to brainstorm
about………. within groups)
 ……………………………….
 ……………………………….

Practical learning Activity


 …………………………………… (Example: Trainees in pair perform
…………………)

Points to Remember (Take home message)

Indicative content 1.3: ..........................................

Learning out come 1.1 : formative assessment

22
Please mix different assessment instruments/tools for
triangulation and relevancy of assessment
Written assessment
 Assessment instruments/tools
 True or false questions
 Multiple choice
 Essay: Question with short responses and Open ended questions
 Case studies

Practical assessment
 Assessment instruments/tools

 Task to be performed with performance checklist/quality product


checklist

References:

Learning outcome 2: Manipulate data with Javascript

Picture/s reflecting the Learning outcome 2

23
Learning outcome 2. Manipulate data with JavaScript

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

Resources
Equipment Tools Materials
 Vscode  Internet
 Node  Electricity
 Computer  Notepad++  Flipchart
 Projector  Sublim  Marker pen
 White board

Advance preparation:
.
.

24
Indicative content 2.2: Using conditional statement

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

25
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

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
}

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

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


<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

28
Theoretical learning Activity
 ………………………………. (example: ask trainees to brainstorm
about………. within groups)
 ……………………………….
 ……………………………….

Practical learning Activity


 …………………………………… (Example: Trainees in pair perform
…………………)

Points to Remember (Take home message)

Indicative content 2.: Using Loop functions in


Javascript

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:

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

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

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)

31
<script>
var table=5;
var i=1;
var tab=0;
while(i<=10)
{
var tab=table*i;
document.write(tab + " ");
i++;
}
</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

32
statement or code block repeatedly as long as an expression is true.
Once the expression becomes false, the loop terminates.
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!
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.

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

34
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
storage
presentation
bluetooth
usb
requestMediaKeySystemAccess
getUserMedia
webkitGetUserMedia
requestMIDIAccess
Exiting from the loop!

35
Theoretical learning Activity
 ………………………………. (example: ask trainees to brainstorm
about………. within groups)
 ……………………………….
 ……………………………….

Practical learning Activity


 …………………………………… (Example: Trainees in pair perform
…………………)

Points to Remember (Take home message)

Using Functions in Javascript [Practical]

Indicative content 2.1.: Using string in JavaScript

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.

36
<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");
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:

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

Theoretical learning Activity


 ………………………………. (example: ask trainees to brainstorm
about………. within groups)
 ……………………………….
 ……………………………….

Practical learning Activity


 …………………………………… (Example: Trainees in pair perform
…………………)

Points to Remember (Take home message)

Using Functions in Javascript [Practical]

Indicative content 2.2. Using Functions in Javascript


[Practical]

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.

38
 Reusability of code: A function can be called multiple times
hence, saving the code.
 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>
<head>
<title>JavaScript Function</title>

39
<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?”

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

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

41
Theoretical learning Activity
 ………………………………. (example: ask trainees to brainstorm
about………. within groups)
 ……………………………….
 ……………………………….

Practical learning Activity


 …………………………………… (Example: Trainees in pair perform
…………………)

Points to Remember (Take home message)

Using Functions in Javascript [Practical]

Indicative content 2.3. ………………………………………………..

42

You might also like