Javascript Fundamentals
Javascript Fundamentals
TRADE: SOFTWARE
DEVELOPMENT
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
1
Learning outcome 1: Apply JavaScript Basic Concepts
Duration: ……….hrs
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:
.
.
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 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
6
The ECMA-262 Specification defined a standard version of the core
JavaScript language.
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>
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.
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
</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)
……………………………….
……………………………….
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>
30
JavaScript local variable
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>
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>
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 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' );
}
17
……………………………….
Operator Description
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
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:
21
Theoretical learning Activity
………………………………. (example: ask trainees to brainstorm
about………. within groups)
……………………………….
……………………………….
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
References:
23
Learning outcome 2. Manipulate data with JavaScript
Duration: ……….hrs
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
JavaScript If-else
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>
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.
28
Theoretical learning Activity
………………………………. (example: ask trainees to brainstorm
about………. within groups)
……………………………….
……………………………….
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:
<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>
<script>
var i=10;
while(i<=12)
{
document.write(i + "<br/>");
i++;
}
</script>
31
<script>
var table=5;
var i=1;
var tab=0;
while(i<=10)
{
var tab=table*i;
document.write(tab + " ");
i++;
}
</script>
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...
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)
……………………………….
……………………………….
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
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>
The following example uses the backslash character to escape the single
quote character in a string:
37
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.
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.
<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.
<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.
<html>
<head>
<title>JavaScript Function</title>
</head>
<body>
<script>
function getInfo()
{
return "Hello PHPTPOINT! How are Things?";
}
document.write(getInfo());
</script>
</body>
</html>
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.
apply() In order to call a function that contains this value and a single
array of arguments.
1. <script>
2. var add=new Function("num1","num2","return num1+num2");
3. document.writeln(add(5,25));
4. </script>
1. <script>
2. var pow=new Function("num1","num2","return
Math.pow(num1,num2)");
3. document.writeln(pow(5,3));
4. </script>
41
Theoretical learning Activity
………………………………. (example: ask trainees to brainstorm
about………. within groups)
……………………………….
……………………………….
42