0% found this document useful (0 votes)
112 views90 pages

Javascript Lesson For Vii and Viii

This document provides an overview of JavaScript concepts and lessons for learning JavaScript, including: - Using HTML editors like Notepad to create and open HTML files that contain JavaScript code. - Covering basic HTML elements and tags, and how to add JavaScript to HTML documents in the head, body, and external files. - Explaining JavaScript concepts like variables, operators, arrays, objects, functions, events, and conditional statements. - Providing examples of building interactive elements like clocks, counters, and calculators using JavaScript. The document outlines a course to teach JavaScript programming fundamentals through creating HTML pages and interactive projects.

Uploaded by

AKSHAJ BAJAJ
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
112 views90 pages

Javascript Lesson For Vii and Viii

This document provides an overview of JavaScript concepts and lessons for learning JavaScript, including: - Using HTML editors like Notepad to create and open HTML files that contain JavaScript code. - Covering basic HTML elements and tags, and how to add JavaScript to HTML documents in the head, body, and external files. - Explaining JavaScript concepts like variables, operators, arrays, objects, functions, events, and conditional statements. - Providing examples of building interactive elements like clocks, counters, and calculators using JavaScript. The document outlines a course to teach JavaScript programming fundamentals through creating HTML pages and interactive projects.

Uploaded by

AKSHAJ BAJAJ
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 90

Innovation Lab: JavaScript

1|Page
Table of Contents
Lesson 1 : HTML in Nutshell ............................................................................................ 5
1.1 HTML & JavaScript Editors ............................................................................................................. 5
1.1.1 How to open Notepad ............................................................................................................. 5
1.1.2 How to create a new HTML document using Notepad. .............................................. 7
1.1.3 How to open an existing HTML file in Notepad: ............................................................ 9
1.1.4 How to open an HTML file in a web browser: ............................................................... 10
1.2 Basic of HTML File ........................................................................................................................... 12
1.3 Title and Headings .......................................................................................................................... 13
1.4 Paragraphs ......................................................................................................................................... 14
1.5 Buttons ............................................................................................................................................... 15

Lesson 2 : Start JavaScript ............................................................................................. 17


2.1 JavaScript in HTML documents .................................................................................................. 17
2.1.1 JavaScript in the head of HTML documents .................................................................. 17
2.1.2 JavaScript in the body of HTML documents .................................................................. 17
2.1.3 JavaScript from an external file: .......................................................................................... 18
2.2 Selection of HTML elements ........................................................................................................ 20

Lesson 3 : Outputs, Functions and Events .................................................................... 22


3.1 JavaScript Output Display ............................................................................................................. 22
3.2 Functions in JavaScript................................................................................................................... 24
3.3 Events ................................................................................................................................................... 26

Lesson 4 : Variables and operators ............................................................................... 30


4.1 Variables.............................................................................................................................................. 30
4.1.1 Declaration of variables ......................................................................................................... 31
4.1.2 Data types of variables .......................................................................................................... 31
4.2 JavaScript Operators ....................................................................................................................... 33
4.2.1 Arithmetic Operators .............................................................................................................. 33
4.2.2 Comparison Operators .......................................................................................................... 35

2|Page
4.2.3 Logical Operators .................................................................................................................... 37
4.2.4 Assignment Operators ........................................................................................................... 38

Lesson 5 : Array and Object ............................................................................................ 41


5.1 JavaScript Array ................................................................................................................................ 41
5.1.1 Array declaration ...................................................................................................................... 41
5.1.2 Array as Collection Data Type ............................................................................................. 43
5.1.3 Index Number ........................................................................................................................... 44
5.1.4 Deleting Elements.................................................................................................................... 45
5.1.5 pop() Method ............................................................................................................................ 46
5.1.6 push() Method .......................................................................................................................... 47
5.1.7 Array Conversion into String ............................................................................................... 48
5.1.8 shift() & unshift() Method ..................................................................................................... 49
5.1.9 Joining Arrays: ........................................................................................................................... 51
5.2 JavaScript object .............................................................................................................................. 52
5.2.1 Declaration of Variable .......................................................................................................... 52

Lesson 6 : Conditional Statements................................................................................. 55


6.1 If statement ........................................................................................................................................ 56
6.2 If...else statement ............................................................................................................................. 56
6.3 If...else if... statement ...................................................................................................................... 58
6.4 Nested if ...statement...................................................................................................................... 60
6.5 Switch statement.............................................................................................................................. 62

Lesson 7: Loops ................................................................................................................ 65


7.1 for Loop ............................................................................................................................................... 65
7.2 while Loop .......................................................................................................................................... 68
7.3 do...while Loop .................................................................................................................................. 69
7.4 for...in Loop ........................................................................................................................................ 71
7.5 for...of Loop ........................................................................................................................................ 72
7.6 Label, break and continue statement ....................................................................................... 73

3|Page
Lesson 8 : Clock & Counter ............................................................................................. 75
8.1 Date object ......................................................................................................................................... 75
8.2 setTimeout & setTimeInterval ..................................................................................................... 76
8.3 Project 1 : Clock ................................................................................................................................ 78
8.4 Project 2 : Counter........................................................................................................................... 79

Lesson 9 : Character counter & Calculator ................................................................... 82


9.1 Project 1: Character counter ........................................................................................................ 82
9.2 Eval() Method .................................................................................................................................... 84
9.3 Project 2: Calculator ........................................................................................................................ 88

4|Page
Lesson 1 : HTML in Nutshell

1.1 HTML & JavaScript Editors


An HTML document (which also contains JavaScript codes) is nothing but a plain text
file. Such a file can be created and modified with the help of a variety of word processor
programs provided that it must be saved in text format and the extension of the file
must be ”*.html”. This is because a web browser does not read a file that is saved in a
common word processor format.

The easiest way to develop a web page is by using Notepad. It is a very simple text
editor and easily available. It can not only be used to create an HTML document, but
also to modify an existing HTML document.

1.1.1 How to open Notepad


There are several ways by which Notepad can be opened, four out of them are
mentioned as follows.

1. Click the Start button, select All Apps, and then navigate to Windows Accessories.
Look for a notepad and click on the icon of Notepad.

5|Page
2. Press Windows (logo)+R, type “notepad” and then select OK as shown below.

3. Search Notepad with the help of search box, type “notepad” in it

6|Page
4. Right-click on a blank area, select new from the context menu. Then click on the
“Text Document”.

1.1.2 How to create a new HTML document using Notepad.


Follow the below-given instructions to create a new HTML document.
1. Open Notepad and start typing HTML codes.
2. Upon completion of HTML codes, click the File on the Menu bar as shown below.

7|Page
3. Then select “Save As…” from the dropdown menu. After that, Save As Window
will open.

4. Navigate and select the desired location for saving the HTML document. Next,
click the “Save as type” which is located at the bottom of the window. By default
setting, the “Text documents (*.txt)” has already been chosen. Click it and it
prompts a dropdown as shown below.

8|Page
5. Now, click “All Files” from the drop-down menu. This allows a text file to save as
an HTML document.

6. In File name: textbox, enter a desired name of the file with extension “.html” and
click Save. For example, the name of the file can be “helloWorld.html” as shown
below.

1.1.3 How to open an existing HTML file in Notepad:


Very often, to edit an existing HTML file, it is required to be opened in Notepad. The
instructions to do that are mentioned below in detail.
1. Navigate the location of an HTML file with the help of Windows Explorer.

2. Select the file and right-click on it. Then choose “Open with” from the context menu.
After that, click Notepad as shown below.

9|Page
3. Subsequently, the selected file will open in Notepad and it can be edited.

1.1.4 How to open an HTML file in a web browser:


There are many ways by which an HTML file can be opened in a web browser. The
explanation of two such ways is mentioned below.

1. Navigate to the location of an HTML file with the help of Windows Explorer and
simply double click on it. Then, the file will open in the default web browser.

2. The second way is mentioned below.


a. Open a web browser and click File on the menu bar. A dropdown menu
appears as shown below.

10 | P a g e
b. Click “Open File…” in the drop-down menu and immediately afterwards an
Open File window pops up. Navigate to the location of the HTML file then
select it and click Open as shown below.

11 | P a g e
1.2 Basic of HTML File
HTML uses a standardized system of markup tags to control various aspects on web
pages such as the font, colour, hyperlink, etc. The first question arises here, what are
markup tags? They are hidden keywords within web pages, which direct web browsers
to format and arrange contents on web pages. The majority of tags work in pairs, each
pair comprises one opening tag and one closing tag. For example, <html> and </html>,
where <html> is an opening tag and </html> is a closing tag.

Irrespective of the contents of web pages, a few markup tags are common and
compulsory across all HTML documents. These are listed below with a brief description.

 <!Document html> : It defines the type of the document and its HTML version. It
helps web browsers to identify the document properly. Therefore, the presence
of this markup tag at the beginning of all HTML documents only once.

 <html> and </html> : All HTML documents begin with <html> and end with
</html>. These tags comprise an entire HTML document within them.
Furthermore, an entire document which is closed inside them is divided into two
parts: head and body.

 <head> and </head> : The head of an HTML document is defined between


<head> and </head>. They are used to keep other tags inside such as <title>,
<links>, etc.

 <body> and </body> : Similarly, the body of an HTML document is defined


between <body> and </body>. All other html tags are used inside them.

To understand the above markup tags, study the following example thoroughly.

<!DOCUMENT html>
<html>
<head>
<title>This is the title of the web page.</title>
</head>
<body>
<p>My first paragraph.</p>
</body>
</html>

12 | P a g e
1.3 Title and Headings
These tags are used to show what a web page is all about. The title tags are used inside
the head of a web page and heading tags are used in the body of web pages. Title tag
sets the title in the toolbar of a web browser, whereas headings tags set headings of a
web page.

Syntax of title tag:


<title>The Title</title>
There are about six types of headings tags, which are available in HTML. Based on the
priority of heading, an appropriate tag can be used. These are <h1></h1>, <h2></h2>,
<h3></h3>, <h4></h4>, <h5></h5> and <h6></h6> . The <h1> </h1> tag is used
to define a heading of highest priority, accordingly <h6></h6> is used to define a
heading of list priority (smallest size). For example,

<!DOCTYPE html>
<html>

<head>
<title>This is title of the page</title>
</head>

<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>
</body>
</html>

13 | P a g e
Output:

1.4 Paragraphs
With the <p></p> tag, the text content on a web page can be arranged into different
paragraphs. A paragraph on a web page always begins with a new line and by default
some space is added before and after a paragraph. Each paragraph begins with an
opening tag <p> and ends with a closing tag </p>. For example,

<!DOCTYPE html>
<html>
<head>
<title>An Example Paragraph</title>
</head>

<body>
<p>This is an example of paragraph to understand that how a paragraph is
seen on a web page.</p>
<p>This is a paragraph which is used to arrange text on a web page.</p>
<p>A space is added automatically before and after of a paragraph on a
web.</p>
</body>
</html>

14 | P a g e
Output:

1.5 Buttons
A button can be added to a web page very easily. A button can have many uses such as
connecting two web pages, playing multimedia, etc. Let’s see how to create a button on
a web page.

<!DOCTYPE html>
<html>
<head>
<title>HTML Button</title>
</head>
<body>
<form action="">
<input type="button" value="Click!">
</form>
</body>
</html>

Output:

There is one more way by which a button can be placed on a web page using <button>
tag. For example,
<!DOCTYPE html>
<html>
<head>
<title>HTML Button</title>
</head>
<body>

15 | P a g e
<h1>Button Element</h1>

<button>Click!</button>
</body>
</html>

Output:

16 | P a g e
Lesson 2 : Start JavaScript

JavaScript is one of the most powerful and flexible languages for web development. It is
also a very common and lightweight programming language which is used almost in all
websites. Generally, it is used in combination with HTML because it interacts with
various HTML elements of web pages. As a result, web pages become interactive.

2.1 JavaScript in HTML documents

2.1.1 JavaScript in the head of HTML documents


JavaScript programming is implemented through JavaScript statements or instructions.
These statements of JavaScript can be placed within the <script>...</script> tags of
HTML. Usually, these script tags are placed within the <head> ... <head/> tags. Let us
understand this description with the help of the following example.

<!DOCTYPE html>
<html>
<head>
<title>JavaScript </title>
<script>

//This is the place where all the statements of JavaScript should be written.
alert("Hello World!");
</script>
</head>
<body>
</body>
</html>

2.1.2 JavaScript in the body of HTML documents


JavaScript statements enclosed within script tags not only can be placed in the head of
the document but also it can be placed in the body of the document. In both cases,
JavaScript statements enclosed within script tags can be placed multiple times in an
HTML document as per the requirement of users. Let us see the above example again by
changing the position of JavaScript.

17 | P a g e
<html>
<head>
<title>JavaScript </title>
</head>
<body>
<script>
//This is the body of the HTML document.
//Make sure all the statement of JavaScript
//should be written within script tags
alert("Hello World!");
</script>
</body>
</html>

2.1.3 JavaScript from an external file:


JavaScript can be implanted from an external file. In this case, all statements of
JavaScript are not included in a corresponding HTML file. However, a separate file is
made to keep all the statements of JavaScript and it is saved with the file extension “.js”.
The path of the “.js” file is provided in the HTML file. Let’s understand this with the help
of the following example.

1. Open the Notepad and write the following code.

18 | P a g e
2. Then, save the file with any name with file extension “.js”.

3. Create a corresponding HTML document with the following code and keep ready
the file location of the “.js” file (Such as “D:\Jscript.js”).

<html>
<head>
<title>JavaScript </title>
<script src="D:\Jscript.js"> </script>
</head>
<body>
</body>
</html>

Paste the path of the “.js file” location in the area which is highlighted with yellow
colour. After that save the HTML file.

4. Now, open this HTML file in a web browser. It shows “Hello World!” text on the
page.
This way one can create and incorporate external JavaScript files in an HTML document.

19 | P a g e
2.2 Selection of HTML elements
As it is already explained, JavaScript is used to add interactivity to web pages. It also
increases the functionality of HTML elements of web pages. To do this, the selection of
HTML elements is the primary requirement. This can be done with the help of an
attribute called the “id” and a JavaScript method or function called the
getElementById("Id_value"). The “id” should be attached to those HTML elements which
are to be selected for upgrades by a JavaScript program. Check the following example
to understand this.

<!DOCTYPE html>
<html>
<head>
<title>Selection of an HTML Element</title>
</head>
<body>
<p>This is an example of the HTML paragraph.</p>
<p>This is an example of the HTML paragraph.</p>
<!--Comment: The following paragraph is selected from attribute id.-->
<p id="para">This is an example of the HTML paragraph.</p>
<p>This is an example of the HTML paragraph.</p>
<p>This is an example of the HTML paragraph.</p>
<script>
document.getElementById("para").innerHTML="The content of this paragraph
has been changed by JavaScript.";
</script>
</body>
</html>

Output:

20 | P a g e
Similarly, more than one HTML element can be selected with “id”. For example,

<!DOCTYPE html>
<html>
<head>
<title>Selection of HTML Elements</title>
</head>
<body>
<h1>This is an example of the HTML Heading 1</h1>
<p>This is an example of the HTML paragraph.</p>
<h2 id="sr1">This is an example of the HTML heading 2 </h2>
<p>This is an example of the HTML paragraph.</p>
<h3>This is an example of the HTML heading 3</h3>
<!--Comment: The following paragraph is selected from attribute id.-->
<p id="para">This is an example of the HTML paragraph.</p>
<p>This is an example of the HTML paragraph.</p>
<h6 id="sr2"></h6>
<p>This is an example of the HTML paragraph.</p>
<script>
document.getElementById("para").innerHTML="Change Made by JavaScript";
document.getElementById("sr1").innerHTML="Change Made by JavaScript";
document.getElementById("sr2").innerHTML="Change Made by JavaScript";
</script>
</body>
</html>

Output:

21 | P a g e
Lesson 3 : Outputs, Functions and Events

This lesson deals with three fundamental aspects of JavaScript: output display, use of
functions and various events. Understanding of three things is extremely important in
Javascript. This lesson explains them one by one.

3.1 JavaScript Output Display


In JavaScript, there are four ways to show outputs on web pages. The methods related
to these four ways are mentioned below.

Sr.
Methods Description
No.
It is used to show outputs by changing the content
1 innerHTML
of HTML elements.
2 document.write() It shows outputs on a web page.
3 window.alert() It exhibits output inside an alert box.
4 console.log() It displays outputs in the console.

Let us grasp this with the subsequent examples.


1. Output display using innerHTML:
<html>
<head><title>Output Display Using innerHTML</title></head>
<body>
<h5>The sum of 20 and 56 is given below.</h5>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 20 + 56;
</script>
</body>
</html>
Output:

22 | P a g e
2. Output Display Using Document.Write():
<!DOCTYPE html>
<html>
<head>
<title> Output Display Using document.write()</title>
</head>
<body>
<h5>The multiplication of 27 and 7 is given below.</h5>
<script>
document.write(27*7);
</script>
</body>
</html>

Output:

3. Output display using windows.alert():


<!DOCTYPE html>
<html>
<head>
<title>Output Display Using windows.alert()</title>
</head>
<body>
<script>
window.alert("Division of 25/5 = " + (25/5));
</script>
</body>
</html>

23 | P a g e
Output:

4. Output display using console.log():


<!DOCTYPE html>
<html>
<head>
<title> Output Display Using console.log():</title>
</head>
<body>
<script>
console.log("subtraction of 41 from 120 = " + (120-41));
</script>
</body>
</html>
Output:
The shortcut keys to open console in Google Chrome: Ctrl + Shift + j

Note: It is recommended that all the JavaScript instruction should be ended with a
semicolon, though it is not compulsory.

3.2 Functions in JavaScript


In JavaScript or any other programming language, the function is a very useful concept.
A function is nothing but a block of codes or a group of statements which performs a
task. A function can be executed several times by calling it as many times as a

24 | P a g e
programmer wants. It provides a feature of code reusability in programming languages.
One more important thing about a function is that it does not execute unless it is called.
One can call a function anytime.
After this, the first question that arises here is how one can create or define a function in
JavaScript. Four points are required to declare a function in the JavaScript.
1. The name of a function is always followed by the keyword “function”.
2. After that place open and close parenthesis or round brackets “( )”
3. Then comes, the open and close braces i.e. curly brackets “{ }”
4. All JavaScript statements are placed inside the curly brackets

The structure of syntax of function:


function anyFunctionName()
{
//JavaScript instructions should be present here.
}

The second question that arises here is how to call a function. In a very simple way, only
by mentioning the name of the function along with open and close parenthesis, the
function can be called.

Let us understand this with the help of an example given below.


<!DOCTYPE html>
<html>
<head>
<title>JavaScript Function</title>
<script>
//define a function
function simplefuction()
{
document.write("This is a very simple example of a function.");
}

// calling the function


simplefuction();
</script>

</head>
<body>
</body>
</html>

25 | P a g e
Output:

3.3 Events
An action that happens and takes place in the system is called the event. It can also be
perceived as a signal which indicates something has happened or has been initiated. In
the event-based programming paradigm, the flow of execution in a program is
determined by the occurrence of various events in the system. For example, the click of
a button, a key pressed, movement of a mouse, loading of a web page, selection of an
option, a message from another program, etc.

Events are also essential for web development. JavaScript interacts with HTML and a big
part of this interaction is based on events that occur when a user or a browser
manipulates a page. Codes of JavaScript can be executed when an HTML event occurs.
An HTML event can be something which either a user does or a browser does. There are
numerous HTML events available and some of them are mentioned below.

Events Attribute Description


Mouse onclick When an element is clicked
ondbclick When an element is double-clicked
oncontextmenu When an element is right-clicked or context menu is
triggered
onmouseover / onmouseout When the cursor is moved over / out of an element.
onmousedown / onmouseup When the button is pressed/released over an
element.
onmousemove When the cursor is moving while it is over an
element
onwheel When the mouse wheel is rolled up and down on an
element.
Document DOMContentLoaded When the HTML document loaded
onload The browser has finished loading the page
Keyboard onkeydown when a keyboard key is being pressed
onkeypress when a keyboard key is pressed
onkeyup when a keyboard key is released.

26 | P a g e
Form/ onreset when a reset button is clicked
input onsubmit When a form is submitted
onfocus When an input element is focused by a user
onselect When an input text is selected by a user
onblur When an input field is left by a user.
onchange When the content of an input field is changed e.g.
an option is selected in the drop-down menu.

The structure of syntax for defining an event is something like this.


<element event = "JavaScript statements">

Where the element can be any HTML element, event is the attribute of HTML
elements. The event can be anything which is mentioned in the second column of the
above table. JavaScript statements can be placed inside the double quotes which are
required to be executed as an event is triggered. For example,

<button onclick="document.getElementById('hd1').innerHTML='Hello'">Click</button>

Let us use detailed examples to understand a few different events of HTML.

1. Click event:
<!DOCTYPE html>
<html>
<head>
<title>Click Event</title>
</head>
<body>
<button onclick="this.innerHTML='Clicked!'">Click Me!</button>
</body>
</html>

Output:

Before the Event take place After the the event taken place

27 | P a g e
2. Double Click Event:
<!DOCTYPE html>

<html>
<head>
<title>Click and double Click Events</title>
</head>
<body>
<button ondblclick="this.innerHTML='Double Clicked!'">Click Me!</button>
</body>
</html>

3. Mouseover and mouseout Events


<!DOCTYPE html>

<html>
<head>
<title>Mouse over and Mouse out Events</title>
</head>
<body>
<h1 onmouseover="style.color='green'" onmouseout="style.color='Blue'">
Move the cursor of the mouse over this text.
</h1>
</body>
</html>

4. Load Event
<!DOCTYPE html>
<html>
<head>
<title>Load Event</title>
<script>
function doStuff() {
alert("The page has been loaded!");
document.getElementById("hd2").innerHTML="This text is also loaded along
with the page.";
}
</script>
</head>
<body onload="doStuff()">
<h2 id="hd2"></h2>
</body>
</html>

28 | P a g e
5. Keydown Event

<!DOCTYPE html>

<html>
<head>
<title>Keydown Event</title>
<script>
function doStuff() {
alert("You pressed a key down inside the text box");
document.getElementById("para").innerHTML ="Keep writing your name.";
}
</script>
</head>
<body>
<h3>
Try to Enter your name in the following Text Box
to see how this function works.</h3>
<input type="text" onkeydown="doStuff()">
<p id="para"></p>
</body>
</html>

29 | P a g e
Lesson 4 : Variables and operators

This chapter is about variables and operators of JavaScript. The concept of variables and
operators might be known to students already because they often encounter variables
and operators in mathematical equations such as x+9 where x is a mathematical variable
and plus (+) sign is an operator.

A variable is a representation of arbitrary numerical values. The concept of variables and


operators in computer programming is somewhat similar. In programming, variables are
used to store values or information which can be manipulated. For more clarity, one can
consider a variable as a container which contains information such as numbers,
character, text, etc. This analogy has very striking similarities, for example, the label of a
container is analogous to the name of a variable and a thing which is in the container is
analogous to the value of a variable.

Operators are symbols which represent different computations. The computation can be
of many types such as arithmetical, logical, conditional, etc. However, among them, the
most common one is arithmetical. There are only four arithmetical operations available
which are known to everyone, that is, addition, subtraction, division and multiplication.

4.1 Variables
Variable is the name of a storage location in JavaScript. There are certain rules in
JavaScript to name a variable. They are mentioned as follows.
1. The name of the variable must be started with a letter (a to z or A to z),
underscore (_), or dollar ($) sign.
2. The numbers (0 to 9) can be used in the name after the first letter. It is invalid to
start the name of a variable with a number.
3. The name of a variable should be unique and must not match with another
existing variable in a program.
One more thing about names in JavaScript is that it is case sensitive. The case sensitive
means the uppercase and lowercase letters are considered as different letters. For
example, “Cat” and “cat” are treated as different names. Therefore, variables with such
case sensitivity are also viewed as different variables in JavaScript.

30 | P a g e
4.1.1 Declaration of variables
To declare a variable in JavaScript, commonly a reserved keyword “var” is used. The
name of a variable is succeeded by the keyword. The structure of the syntax in his case
should be the same as follows.

var variableName;

Using the assignment operator “=”, one can store data into a variable. Let us understand
the declaration and initialisation of a variable with the help of the following example.

// declaration of a variable
var message;

// storing the string into the variable


message = "Hi!";

The declaration and initialisation of multiple variables are possible in a single line. For
example,

var user ="Michael", age=24, gender="male";

Make a note that a variable in JavaScript can be declared without the keyword “var”.

4.1.2 Data types of variables


From common sense, one can easily say that data can be of different types such as
characters, string, number, etc. The number data type can be categorised further into
various types such as integer, fraction, etc. While dealing with data, a program must be
aware of the nature of data before performing any type of computation.

In computer programming, the data type is a characteristic of data which instructs a


program on how to treat data. It describes the different types of data which are stored
in variables. Suppose a variable is declared and initialized with a value “125”. It means
the data type of this variable is an integer. This implies that this variable is used to store
positive or negative numbers. All programmers need to learn and gain a proper
understanding of this idea.

31 | P a g e
Like all other programming languages, JavaScript also supports the feature of data
types. JavaScript has about seven data types. These data types are categorised into two
categories: primitive and non-primitive. This lesson only talks about primitive data
types. They are as follows.
Data Type Description Declaration and Initialization

The string should be initialized with a single or


It is a sequence of characters double quote e.g.
String
e.g. "hello John!", etc. var message = 'Hello!'
var message = "Hello!"

It is numeric values e.g. 100, It can be written with or without decimals.


Number var Num1 = 40.00;
100, etc. var Num2 = 40;

It can only have two values Declaration and Initialization e.g.


boolean var boolVar1 = true;
either false or true. var boolVar2 = false;
Value is undefined, thus type is undefined e.g.
Undefined A variable without value
var car;

Null It is null i.e. no value at all myvar = null;

Let us see all the data types in the following programs.


<!DOCTYPE html>
<html>
<head>
<title>Data Types</title>
<script>
//Declaration and initialization of number
var NumVar = 100;
document.write("Number: " + NumVar +"<br>")

//Declaration and initialization of string


var stringVar = "Steve";
document.write("String: "+ stringVar+"<br>");

//Declaration and initialization of boolean


var BoolVar = true;
document.write("boolean: "+ BoolVar +"<br>");

//Declaration and initialization of undefined


var undefVar = undefined;
document.write("Undefined: "+ undefVar +"<br>");
//Declaration and initialization of null
var NullVar = null;
document.write("Null: "+ NullVar +"<br>");
32 | P a g e
</script>
</head>
<body>
</body>
</html>

4.2 JavaScript Operators


JavaScript supports multiple types of operators. The categories of these operators are
mentioned below.
 Arithmetic Operators
 Comparison Operators
 Logical Operators
 Assignment Operators
 Conditional Operators
The above-mentioned operators are discussed below.

4.2.1 Arithmetic Operators


The arithmetic operators are used to perform an arithmetical operation on numeric
operands. The majority of the operators operate between two numeric operands, but
some operators can operate on one operand. Explore the following table carefully.
Operators Description

+ It is used to add two or more numerical operands such as x+y, 3+5+4, etc.

- It is used to subtract a right operand from a left for example x – y.

* It is the multiplication operator which is used to multiply numeric operands.


It is the division operator which is used to divide a left operand by a right operand.
/ For instance, a/b.
It is the modulus operator which is used to get the remainder of two operands. For
% example, 3%2 returns 1 because it is a remainder.

++ It is an increment operator and it increases the value of an operand by one.

-- It is a decrement operator and it decreases the value of an operand by one.


It is the exponential operator, it makes the first operand base and second operand as
** power. For example, 2**3, which returns the value 8.

33 | P a g e
The following example shows how these operators work.
<html>
<head>
<title> Arithmetic Operators</title>
</head>
<body>
<script>
//Declaration and initialization of variables
var x = 57;
var y = 42;
var z = " Total ";
var lb="<br>"
var l ="<hr>"

//display the values


document.write("x = " + x);
document.write(lb);
document.write("y = " + y);
document.write(l);

//using the addition operator


document.write("x + y : ");
answer = x+y; // declaration without the “var” keyboard
document.write(z + answer);
document.write(lb + lb + lb);

//using the subtraction operator


document.write("x - y : ");
answer = x-y;
document.write(z + answer);
document.write(lb + lb + lb);

//using the division operator


document.write("x / y : ");
answer = x/y;
document.write(z + answer);
document.write(lb + lb + lb);

//using the multiplication operator


document.write("x * y : ");
answer = x*y;
document.write(z + answer);
document.write(lb + lb + lb);

//using the exponential operator

34 | P a g e
document.write("x**2 : ");
answer = x**2;
document.write(answer);
document.write(lb + lb + lb);

//using the increment operator


document.write("++ y : ");
answer = ++y;
document.write(answer);
document.write(lb + lb + lb);

//using the decrement operator


document.write("-- x : ");
answer = --y;
document.write(answer);
document.write(lb + lb + lb);
</script>
</body>
</html>

4.2.2 Comparison Operators


In a programming language, comparison operators are used to compare the values of
two operands or variables and return a boolean i.e. true or false. There are various types
of comparison operators available in JavaScript. The following is a list of some important
comparison operators with their descriptions.

Name of
Operator Description Example
operator
== Is equal to It compares the equality of two operands. (50 ==75) = false
!= Not equal to It compares the inequality of two operands (50!=75) = true
It checks whether an operand on left is
> Greater than (75 > 50) = true
greater than an operand on the right
It checks whether an operand on left is less
< Less than (75 < 50) = false
than an operand on the right
Greater than It checks whether an operand on left is
>= greater than or equal to an operand on the (75 >= 50) = true
or equal to
right
Less than or It checks whether an operand on left is less
<= (75 <=50) = false
equal to than or equal to an operand on the right

35 | P a g e
The following example demonstrates how these operators work.

<html>
<head>
<title> Comparison operators</title>

<script>
/*Declaration and initialization of variables*/
var x= 50, y = 75, lb = "<br>";
document.write("x = " + x + lb +"y = "+ y);
document.write(lb + lb);

/*Equality comparison*/
document.write("(x == y) => ");
answer = ( x == y);
document.write(answer);
document.write(lb + lb);

/*Inequality comparison*/
document.write("(x < y) => ");
answer = (x < y);
document.write(answer);
document.write(lb + lb);

/*To compare whether the right side variable is


greater than the left side variable.*/
document.write("(x > y) => ");
answer = (x > y);
document.write(answer);
document.write(lb + lb);

/*To compare whether the right side variable is


less than the left side variable.*/
document.write("(x != y) => ");
answer = (x != y);
document.write(answer);
document.write(lb + lb);

/*To compare whether the right side variable is


greater than or equal to the left side variable.*/
document.write("(x >= y) => ");
answer = (x >= y);
document.write(answer);

36 | P a g e
document.write(lb + lb);

/*To compare whether the right side variable is


greater than or less to the left side variable.*/
document.write("(x <= y) => ");
answer = (x <= y);
document.write(answer);
document.write(lb + lb);
</script>
</head>
<body>
</body>
</html>

4.2.3 Logical Operators


Logical operators are used to combine conditional statements. There are various logical
operators available in JavaScript as follows.

Name of
Operator Description Example
operator
(10==20) && (20==33) = false
&& And True if both operands are true (50>35) &&(60<75) = true
(23<23)&&(50>45) = false
(10==20) || (20>=33) = false
True if either one out of two
|| Or (10<20) || (20 != 33) = true
operands is true
(45>=75) || (20<33) = true
!(20==20) = false
! Not True if an operand is not true !(10>20) = true
!(10<20) = true

For clarity go through the following table.

A B A && B A || B !A
False False False False True
False True False True True
True False False True False
True True True True False

37 | P a g e
The following example demonstrates how these operators work.

<!DOCTYPE html>
<html>
<head>
<title>Logical Operators</title>
<script>
//Declaration and initialization of variables
var A = 50, B = 75, lb = "<br>";
document.write("A = " + A + lb + "B = " + B);
document.write(lb + lb);

// Logical AND
document.write("( (A < B) && (B >= A) ) => ");
answer = ((A<B) && (B>=A));
document.write(answer);
document.write(lb + lb);

//Logical OR
document.write("( (A==B) || (B<=A)) => ");
answer = ( (A==B) || (B<=A) );
document.write(answer);
document.write(lb + lb);

//Logical NOT
document.write("!( A != B) => ");
answer = (!( A != B));
document.write(answer);
document.write(lb + lb);
</script>
</head>
<body>
</body>
</html>

4.2.4 Assignment Operators


The assignment operators are used to assign values to variables. The following
operators are known as JavaScript assignment operators.

38 | P a g e
Operator Name of operators Description Example
It assigns the value of right operand var x = 75
= Assign
into left operand.
It adds both right and left operands, var x =50;
+= Add and assign and assigns the result into the left x += 75;
operand. Then, x = 125
It subtracts the value of right operand var x =75;
-= Subtract and assign from the value of left operand and x -=50;
assigns the result into left operand. Then, x = 25
It multiplies right and left operands, var x = 50;
*= Multiply and assign and assigns the result to the left x * = 75;
operand. Then, x = 3750
It divides the value of left operand by var x = 50;
/= Divide and assign the value of right operand and assigns x /= 5;
the result to left operand. Then, x = 10
It assigns the reminder to left operand var x =50;
%= Modulus and assign after dividing left operand by right x %= 3;
operands. Then, x = 2

For more clarity also go through the following table.


Example Equivalent form
x=y x=y
x += y x=x+y
x -= y x=x-y
x *= y x=x*y
x /= y x=x/y
x %= y x=x%

The following example demonstrates how these operators work.


<html>
<title>Assignment Operators</title>
<script>
var lb = "<br>";

//Function to initialize the variables again and again


function restore(){
x = 75, y = 50;
document.write("x = " + x + lb +"y = "+ y);
document.write(lb);
}

//Function to display the answer

39 | P a g e
function display() {
document.write(answer);
document.write(lb + lb);
}

//Assign
restore();
document.write(" x = y => x = ");
answer = (x = y);
display();

//Add and assign


restore();
document.write(" x += y => x = ");
answer = (x += y);
display();

//Subtract and assign


restore();
document.write(" x -= y => x = ");
answer = (x -= y);
display();

//Multiply and assign


restore();
document.write(" x *= y => x = ");
answer = (x *= y);
display();

//Divide and assign


restore();
document.write(" x /= y => x = ");
answer = (x /= y);
display();

//Modulus and assign


restore();
document.write(" x %= y => x = ");
answer = (x %= y);
display();
</script>
<body> </body>
</html>

40 | P a g e
Lesson 5 : Array and Object

Arrays and objects are both non-primitive data types. Unlike primitive data types, they
are defined by programmers. They are also mutable means their state can be modified
after they are created.

5.1 JavaScript Array


An array is a data structure that contains a collection of elements in which each element
is identified by an index or key. In the context of JavaScript, an array is a variable which
is used to store more than one value. Commonly, it is used when there is a requirement
of storing a list or collection of elements and accessing each element or all the elements
by using only one variable.

5.1.1 Array declaration


There are two ways by which an array can be declared or created in JavaScript programs.

1. First Method:
The first method is well known and generally used for creating an array. The syntax for
that is mentioned as follows.

var array_name = [value1, value2, ...];

Let us understand this with the help of the following example.


<html>
<head>
<title>JavaScript Array</title>
</head>

<body>
<h2 >Fruits: </h2> <p id="para1"></p>
<br><br>
<h2 >Vegetables: </h2> <p id="para2"></p>
<script>
// Array declaration for the list of fruits
var fruit = [" Mangos", " Grapes"," Apple",
" Apricots", " Orange", " Banana Fresh",
" Avocados", " Guava", "Lichi", " Papaya",
" Sapota", " Water Melons"];

41 | P a g e
//Array declaration for the list of vegetable
var Vegetables = [' Ladyfinger', ' Cauliflower', ' Bitter gourd',
' French Beans', ' Cabbage', ' Ridge gourd',
' Spinach', ' Fenugreek',];

document.getElementById("para1").innerHTML=fruit;
document.getElementById("para2").innerHTML=Vegetables;
</script>
</body>
</html>

2. Second Method:
This method is not as popular as the previous method. The syntax for that is mentioned
as follows.
var array_name = new Array();

Let us understand this with the help of the following example.


<!DOCTYPE html>
<html>
<head>
<title>Document</title>
</head>
<body>
<h1>List of denomination of currency in India: </h1>
<p id="para1"></p>

<h1>List of animals: </h1>


<p id="para3"></p>

<script>
// Initializing while declaring
var denomination = new Array(10, 20, 50, 100, 200, 500, 2000);

//Creates an array with element 1BHK


var animals = new Array( "elephant", " rhinoceros", " Bengal tiger",
" lion", " leopard", " snow leopard",
" blackbuck", " bear");

document.getElementById("para1").innerHTML= denomination;
document.getElementById("para3").innerHTML= animals;
</script>
</body>
</html>

42 | P a g e
It is not compulsory to initialise an array at the time of declaration, one can initialise an
array after declaration. To understand this study the following example.

<!DOCTYPE html>
<html>
<head>
<title>Initialization of Array</title>
</head>
<body>
<h1>List of flowers: </h1>
<p id="para"></p>
<script>
// Creates an array of 5 undefined elements
var flowers = new Array(5);

// Now assign values to the array


flowers[0] = " Orchids";
flowers[1] = " Marigold";
flowers[2] = " Lotus";
flowers[3] = " Rose";
flowers[4] = " Hibiscus";

document.getElementById("para").innerHTML= flowers;
</script>
</body>
</html>

Output:

In the above example, the number within the square brackets which is placed next to the
array variable is called the index.

5.1.2 Array as Collection Data Type


An array can be used to store a variety of different data types or elements. For example,
one can create an array which consists of a string, number and boolean. Go through the
following code to understand this.

43 | P a g e
<!DOCTYPE html>
<html>
<head>
<title> Initializing arrays with different data types</title>
</head>
<body>
<h1>Members: </h1>
<p id="para"></p>
<script>
// Creates an array which stores number, string and boolean
var member = [" John", 28," Michael", 16," Steve", 19,
" Adam", 22," Rose", 17, true];
document.getElementById("para").innerHTML= member;
</script>
</body>
</html>

Output:

5.1.3 Index Number


Each element of an array can be accessed using an index number of the element. The
index number of the first element of an array is always 0. An index number is always
enclosed within a square bracket as [0], [1] for the second element, [2] for the third
element, [3] for the third element, etc. The name of an array is followed by the index
number of an element. Examine the following example to grasp the concept of the
index number in little depth.

<!DOCTYPE html>
<html>
<head>
<title>Index Number</title>
</head>
<body>
<h4>The initial list of elements in the Array.</h4>
<p id="para1"></p><br><br>

<h4>After the replacement of an elements using the index number.</h4>

44 | P a g e
<p id="para2"></p>

<script>
var grains = ['wheat', ' rye', ' triticale', ' oats',
' oat bran', ' brown rice', ' flaxseed'];

document.getElementById("para1").innerHTML=grains;

//Access the first element of the array to replace its value.


grains[0] = "barely";
document.getElementById("para2").innerHTML=grains;
</script>
</body>
</html>

Output:

5.1.4 Deleting Elements


An element of an array can be removed with the help of operator delete. To do this, just
specify the name of an array and the index number of the element which is required to
be deleted. For clarity study the following example.

<!DOCTYPE html>
<html>
<head>
<title>Index Number</title>
</head>
<body>
<h4>The initial list of elements in the Array.</h4>
<p id="para1"></p><br><br>

45 | P a g e
<h4>Delete the first item of above mentioned list.</h4>
<button type="button" onclick="toRemove()">Delete the first item!</button>

<script>
var grains = ['wheat', ' rye', ' triticale', ' oats',
' oat bran', ' brown rice', ' flaxseed'];

document.getElementById("para1").innerHTML="Initially: "+grains;

function toRemove(){
//Delete the first element
delete grains[0];
document.getElementById("para1").innerHTML="Updated Array:"+ grains;
}
</script>
</body>
</html>

Output:

5.1.5 pop() Method


The last element of an array can be removed very easily using the JavaScript method
pop(). It does not require to know the length of an array. The length means how many
elements are stored in an array. Let us see this method in action in this example.

<!DOCTYPE html>
<html>
<head>
<title>Method pop() in JavaScript</title>
</head>

46 | P a g e
<body>
<h3>All the elements of the Array.</h3>
<p id="para1"></p><br>
<h3>The array, after the pop() method executed once. </h3>
<p id="para2"></p><br>
<h3>The array, after the pop() method executed again.</h3>
<p id="para3"></p>
<script>
var animals = [" elephant", " rhinoceros", " tiger",
" lion", " leopard", " snow leopard",
" blackbuck", " bear"];

document.getElementById("para1").innerHTML=animals;
animals.pop();
document.getElementById("para2").innerHTML=animals;
animals.pop();
document.getElementById("para3").innerHTML=animals;

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

Output:

5.1.6 push() Method


Using the push() method, one can add a new element at the end of an array without
knowing the length of an array. It is faster than usual. To understand this study the
following example.

47 | P a g e
<!DOCTYPE html>
<html>
<head>
<title>Method push() in JavaScript</title>
</head>
<body>
<h3>Initially the array contains the following number of elements.</h3>
<p id="para1"></p><br>
<h3>After pushing one more element. </h3>
<p id="para2"></p><br>
<h3>After pushing one more element. </h3>
<p id="para3"></p>
<script>
var stones = ["Limestone", "Sandstone", "Soapstone",
"Fossil stone", "Travertine", "Marble",
"Slate",];

document.getElementById("para1").innerHTML=stones;
stones.push("Serpentine");
document.getElementById("para2").innerHTML=stones;
stones.push("Granite");
document.getElementById("para3").innerHTML=stones;
</script>
</body>
</html>

Output:

5.1.7 Array Conversion into String


Using the toString() method, an array can be converted into a string. All the elements in
the string will be separated from one another by commas.

48 | P a g e
<!DOCTYPE html>
<html>
<head>
<title>Method toString() </title>
</head>
<body>
<h3>The array of seasons are mentioned below.</h3>
<p id="para1"></p>
<script>
var seasons = ["winter", " spring", " summer", " autumn",];
document.getElementById("para1").innerHTML= seasons.toString();
</script>
</body>
</html>

Output:

5.1.8 shift() & unshift() Method


Using this method, the first element of an array can be deleted and then it shifts the rest
of the elements to a lower index (by one).
<!DOCTYPE html>
<html>
<head>
<title>Method Shift() </title>
</head>
<body>
<h3>Initially, the array of atmosphere are mentioned below.</h3>
<p id="para1"></p>
<h3>After the execution of shift() method.</h3>
<p id="para2"></p>
<script>
var atmosphere = ["Troposphere", "Stratosphere", "Mesosphere",
"Thermosphere", "Exosphere"];
document.getElementById("para1").innerHTML = atmosphere;
atmosphere.shift();
document.getElementById("para2").innerHTML = atmosphere;
</script>
</body>
</html>

49 | P a g e
Output:

Using the unshift() method an element can be added at the beginning of the array.
<!DOCTYPE html>
<html>
<head>
<title>Unshift() Method</title>
</head>
<body>
<h3>List of fruits is given below.</h3>
<p id="para"></p> <br><br>
<label>Enter the Name of a Fruit: </label>
<input type="text" id="ip">
<button onclick="doStuff()">Add</button>
<script>
var fruits = [" Apple", " Banana", " Mango", " Orange", " Sapota"];

document.getElementById("para").innerHTML = fruits;

function doStuff() {
//Store the value in a variable from the input field.
x = document.getElementById("ip").value;
//Remove the text from the input field.
document.getElementById("ip").value = "";
//Add the value in the array using the variable.
fruits.unshift(x);
//Display the array on the web page.
document.getElementById("para").innerHTML = fruits;
}
</script>
</body>
</html>

50 | P a g e
Output:

5.1.9 Joining Arrays:


With the help of concat() method, an array can be joint or merge with another array. See
in the following example.
<!DOCTYPE html>
<html>
<head>
<title>Concatenate Arrays</title>
</head>
<body>
<P id="para1"></P><br>
<P id="para2"></P><br>
<P id="para3"></P><br>
<script>
var wildAnimals=['Monkey', ' Panda', ' Zebra', ' Gorilla',
'Walrus', ' Leopard', ' Wolf'];

var domesticAnimals= ['Sheep', ' Horses', ' Donkeys',


'Camels', ' Buffaloes', ' Goats',
'Cow', ' Duck', ' Chicken'];

//Marge both the above arrays.


var animals = wildAnimals.concat(domesticAnimals);

document.getElementById("para1").innerHTML
= "<b>Wild Animals:</b>"+wildAnimals;
document.getElementById("para2").innerHTML
= "<b>Domestic Animals:</b>"+domesticAnimals;
document.getElementById("para3").innerHTML
= "<b>Animals:</b>"+animals;
</script>
</body>
</html>

51 | P a g e
Output:

5.2 JavaScript object


In JavaScript, objects are data types but they are non-primitive. They are used to define
variables. Variables which are defined as objects are almost like any other variable.
However, there are certain differences too. They can have more than one value as
properties and methods. The properties of an object can have any value like primitive
data types such as numbers, strings, booleans, etc. On the other hand, methods are
nothing but functions.

5.2.1 Declaration of Variable


Objects are variable and like all other variables, it is required to be declared. There are
two ways in which an object can be created. The first way of the declaration is
mentioned below.
var object_Name = {property1:value1, property2:value2...};

Let us see this type of declaration in the following example:


<!DOCTYPE html>
<html>
<head>
<title>Object Declaration</title>
</head>
<body>
<script>
// Declare object
var student = {rn:34, name:"Neha Sharma", sbj:"History", mrk:"87"};

document.write("Roll No.: " +student.rn+"<br>"+ "Full Name: "


+ student.name+"<br>"+"Subject: "+ student.sbj
+"<br>"+"Mark: "+student.mrk);
</script>
</body>
</html>

52 | P a g e
The second way is mentioned below.

var object_Name = new Object();

Let us also see this type of declaration in the following example:


<!DOCTYPE html>
<html>
<head>
<title>Object Declaration</title>
</head>
<body>
<script>
// Declare object
var student = new Object();
student.rn=34;
student.name="Neha Sharma";
student.sbj="History";
student.mrk="87";

document.write("Roll No.: " +student.rn+"<br>"+ "Full Name: "


+ student.name+"<br>"+"Subject: "+ student.sbj
+"<br>"+"Mark: "+student.mrk);
</script>
</body>
</html>

Output:

53 | P a g e
In both the above examples the objects possess only properties. However, in the
following example, an object also holds a function.

<!DOCTYPE html>
<html>
<head>
<title>An Object with Methods</title>
</head>
<body>
<h4>The Report Card of a student</h4>
<button onclick="studentInfo.fun()">Click</button>

<script>
var studentInfo =
{
rn: 22,
name: "Neha Sharma",
Sbj: "History",
mrk: 82,
fun: function()
{
document.write("Roll No.: " +this.rn+"<br>"+
"Full Name: "+ this.name+"<br>"+"Subject: "+
this.sbj+"<br>"+"Mark: "+this.mrk);
}
}
</script>
</body>
</html>

Output:

After the click event:

54 | P a g e
Lesson 6 : Conditional Statements

As it is already known, the instructions of a computer program are called statements.


Various statements have been encountered throughout this course. However, this lesson
focuses on special statements called conditional statements. Conditional statements
execute only when certain boolean conditions are met. These conditions are specified in
programs by programmers. In such conditions, testing takes place by comparing a
variable against a value.

Conditional statements in programming are used to control the flow of executions of


statements in programs based on different conditions. When a condition is true, then all
the statements which are related to it will be executed. If the condition is false, then the
other set of statements will be executed. Thus, conditional statements are helpful in
decision making in programs. The entire discussion of conditional statements can be
summarised in the following flow chart diagram.

There are a variety of conditional statements available in JavaScript. This lesson


describes them one by one.

55 | P a g e
6.1 If statement
In this, a set of statements executes only when a specified condition is true. If the
condition is false, then those statements cannot be executed.

The syntax for an if statement is as follows.


if (condition)
{
statement 1;
statement 2;
.
.
.
statement n;
}

See the example below to understand the use of this conditional statement.
<html>
<head>
<title> If Conditional statement.</title>
</head>
<body>
<script>
var age;
age = 21;
if (age>18)
{
document.write("You are eligible to vote in the public election.");
}
</script>
</body>
</html>

Output:

6.2 If...else statement


This type of conditional statements gives little greater control over the execution flow of
programs. In this, statements are executed if a specific condition is true. Otherwise,

56 | P a g e
another set of statements are executed that are present after the “else” keyword and
enclosed in braces.

The syntax for an if ... else statement is as follows.


if (condition)
{
statement 1;
statement 2;
.
.
.
statement n;
}

else
{
statement 1;
statement 2;
.
.
.
statement n;
}

See the example below to understand the use of this conditional statement.
<html>
<head>
<title> If Conditional statement</title>
</head>
<body>
<h3>To verify whether you are eligible for voting or not.</h3>
<label>Enter Your Age: </label> <input type="number" id="txtinpt">
<button type="button" onclick="fun()"> Click!</button>
<h3 id="hd"></h3>

<script>
function fun()
{
age = document.getElementById("txtinpt").value;
if (age >= 18)
{
document.getElementById("hd").innerHTML="You are eligible to vote.";
}

57 | P a g e
else
{
document.getElementById("hd").innerHTML=
"You are not eligible to vote.";
}
}
</script>
</body>
</html>

Output:

Having entered a random age and button clicked event, the output is as follows.

Having entered another random age and button clicked event, the output is as follows.

6.3 If...else if... statement


This is an advanced conditional statement, in which more than one condition can be
tested in order to execute appropriate block statements. This is very helpful to make
correct decisions by testing several conditions. The syntax for an if...else if.... statement is
as follows.

if (condition) {
statement1;
statement2;
...
}
58 | P a g e
else if (condition) {
statement1;
statement1;
...
}else {
statement1;
statement2;
...
}
...

See the example below to understand the use of this conditional statement.
<html>
<head>
<title> If else if Conditional statement</title>
</head>
<body>
<label> Enter Any number: </label>
<input type="number" id="txtinpt">
<button type="button" onclick="fun()">
Click!</button>
<h3 id="hd"></h3>

<script>
function fun()
{
number = document.getElementById("txtinpt").value;
document.getElementById("txtinpt").value=" ";
if (number > 0)
{
document.getElementById("hd").innerHTML
="You have entered the positive number";
}
else if (number < 0)
{
document.getElementById("hd").innerHTML
="You have entered the negative number";
}
else
{
document.getElementById("hd").innerHTML
="You have entered zero.";
}
}
</script>

59 | P a g e
</body>
</html>

Output:

For a positive number, the output is as follows.

For a negative number, the output is as follows.

6.4 Nested if ...statement


A nested if statement is an if statement within another if statement. In which, when the
condition of outer if statement is true, then the condition of inner if statement is tested.
The nested if statement allows the programmer to check more than one condition to
execute a statement. It increases the decision making capability of a program several-
fold.
Syntax of Nested if else statement:
if(condition) {
if(condition2) { statements; }
else {statements;}
}
else {
statements;
}

See the example below to understand the use of this conditional statement.
<html>
<head>
<title> Nested If statement</title>

60 | P a g e
</head>
<body>
<h3>Find out the greater number.</h3>
<!-- accept the inputs from users -->
<label>Enter 1st Number: </label>
<input type="number" id="num1">
<label>Enter 2nd Number: </label>
<input type="number" id="num2">
<button type="button" onclick="fun()">
Click!</button>

<h3 id="hd1"></h3>
<h3 id="hd2"></h3>

<script>
function fun()
{
no1 = document.getElementById("num1").value;
no2 = document.getElementById("num2").value;

if ( no1 != no2)
{
document.getElementById("hd1").innerHTML
="Both the numbers are not same.";

if(no1 > no2)


{
document.getElementById("hd2").innerHTML
="1st number is greater than 2nd Number.";
}
else{
document.getElementById("hd2").innerHTML
="2nd number is greater than 1st Number.";
}
}
else
{
document.getElementById("hd1").innerHTML
="Both the numbers are same.";
}
}
</script>
</body>
</html>

61 | P a g e
Output:

6.5 Switch statement


Like an if statement, a switch statement also controls the flow of execution of programs.
In which the value of a variable or expression is used to change the flow of execution of
block statements in a program. It means a switch statement decides out many block
statements which one is required to be executed as per the contemporary condition in
a program. In short, it is used to perform different actions based on different conditions.
Syntax of switch statement:
switch (expression) {
case condition1:
//block statements;
break;

case conditon2:
//block statements;
break;

case condition2:
//block statements;
break;

default:
//block statement;
}

The keyword break is used to end the execution of statements within a switch
statement. If it gets missed by a programmer then each statement is executed
needlessly within the switch statement.

62 | P a g e
See the example below to understand the use of this conditional statement.
<html>
<head>
<Title>Switch statement</Title>
</head>
<body>
<h2>Performance Tracker Page</h2>
<layer>Enter your Grade of the Last Semester: </layer>
<input type="text" id="txtip">
<button type="button" onclick="fun()"> Click </button>
<h4 id="hd1"></h4>

<script>
function fun()
{
grade = document.getElementById("txtip").value;

switch (grade)
{
case 'A': document.getElementById("hd1").innerHTML="Great job!";
break;

case 'B': document.getElementById("hd1").innerHTML="Good job!";


break;

case 'C': document.getElementById("hd1").innerHTML="Passed!";


break;

case 'D': document.getElementById("hd1").innerHTML


="Not so good!";
break;

case 'F': document.getElementById("hd1").innerHTML="Failed!";


break;

default: document.getElementById("hd1").innerHTML
="Provide Valid Grade!";
}
}
</script>
</body>
</html>

63 | P a g e
Output:

Note: Try the same program without a break statement and find out the difference in
the output.

64 | P a g e
Lesson 7: Loops
In computer programming, loops are programming structures which are used to
execute certain sequences of statements until a specific condition is not met. Loops
enable programmers to reuse a set of statements without writing the same statements
again and again in a program. It reduces the length of a program drastically and makes
it very small and brief. Suppose, a program wants to print the same message 100 times,
but writing the same printing statement 100 times is not a wise idea. The reasons are
very simple, it is cumbersome, time-consuming and the length of the program becomes
unusually long. Instead, if a program uses a loop then the entire program summarises
within a few lines of code without any large changes.

There are various types of loops available in JavaScript to repeat a set of lines of codes
such as for, do…while, while, for…in and for..of. This lesson discusses all the loops in
brief.

7.1 for Loop


The for loop is a programming structure which reiterates a block of statements which
are placed in the body of the loop. While executing the statements, again and again,
the for loop constantly checks for certain conditions and these conditions must be true
for uninterrupted reiteration. It stops the execution of block statements when the
conditions become false.

The syntax of a for loop in JavaScript is mentioned below.


for (initialization; condition; increment)
{
//statement or statements;
}

The flow of execution in a for loop is mentioned below.

 Initialisation: This component executes first in the loop. This is only used to
declare and initialise variables. It is invalid to place any other statement here.
Make sure that any declaration and initialisation must be terminated with a
semicolon.

65 | P a g e
 Condition: This place is where the condition is evaluated. The body of the loop
(the part of a loop enclosed between curly brackets) is executed only when the
condition is true. When the condition becomes false, then the body of the loop is
not executed because the flow of execution jumps to the next statement which
comes just after the loop.
 Increment: After the execution of the body of the loop is completed, the flow of
execution jumps to the increment. Here, the value of the loop controlling
variable, either increments or decrements, depending upon the operator which is
used with it.
 After this, the condition of the loop is evaluated again and if it is true then all the
remaining steps are executed in the same order as mentioned above. This
procedure continues until the condition becomes false.

The following diagram reinforces the above discussion briefly.

66 | P a g e
A for loop is used when a programmer knows beforehand how many times a set of
instructions are required to be executed over and over again. Let us understand the for
loop with an example which is mentioned below.

<!DOCTYPE html>
<html>
<head>
<title> For loop</title>
</head>
<body>

<p>Click the following button to write 100 times,


<q>Sorry! I will not do it again.</q></p>

<button onclick="SorryFunc()">Click Me!</button>

<p id="para"></p>

<script>
function SorryFunc()
{
var Apologies = "";
var i;
for (i = 1; i < 101; i++)
{
Apologies += i+". "+
"<i>Sorry! I will not do it again.</i>"+"<br>";
}
document.getElementById("para").innerHTML = Apologies;
}
</script>
</body>
</html>

Output:

67 | P a g e
7.2 while Loop
Like the for loop, it is also used to execute a set of statements repeatedly until a certain
condition is met. Generally, it is used in a situation when a programmer does not know
how many times a set of statements in the body of the loop needs to be executed.

The syntax of a while loop in JavaScript is mentioned below.

while (condition) {
//code block to be executed.
}

The structure of the while loop does not have various components like the for loop. It is
rather more simple and straightforward in which the condition is stated first. If it is true,
then the statement or statements in the body of the loop is/are executed. After that, it
again tests the condition whether it is true or false. If it is true, then it executes the body.
The same cycle will continue until the condition becomes false, then the flow of
execution jumps to the next statement after the loop.

The following diagram reinforces the above discussion briefly.

68 | P a g e
Let us understand the while loop with an example which is mentioned below.

<!DOCTYPE html>
<html>
<head>
<title> For loop</title>
</head>
<body>

<p>
Click the following button to write 100 times,
<q>Sorry! I will not do it again.</q>
</p>

<button onclick="SorryFunc()">Click Me!</button>

<p id="para"></p>

<script>
function SorryFunc() {
var Apologies = "";
var i=0;
while(i<101) {
Apologies += i+". "+"<i> Sorry! I will not do it again.</i>"+"<br>";
i++;
}
document.getElementById("para").innerHTML = Apologies;
}
</script>

</body>
</html>

7.3 do...while Loop


A do…while loop is the same as a while loop, except that it executes the block codes in
the body of the loop at least one time for sure. It is because in a do…while loop, first the
code block in the body is executed and then the condition is tested whether it is true or
not. After that, if the condition is found true then the body is executed again. This cycle
continues until the condition becomes false.

69 | P a g e
The syntax of a do…while loop in JavaScript is mentioned below.

do {
//block code to be executed
} while (condition);

The following diagram reinforces the above concept concisely.

Let us understand the do…while loop with an example which is mentioned below.
<!DOCTYPE html>
<html>
<head>
<title>do...while Loop</title>
</head>
<body>
<h3>Click to display reverse counting from 1000 to 1</h3>
<button type="button" onclick="revCount()">Click!</button>
<h3 id="hd"> </h3>
<p id="para"></p>

<script>
function revCount()
{
var num = 1000;

70 | P a g e
var i = ""

do {
i += num + "<br>";
num--;
} while ( num > 0)

document.getElementById("hd").innerHTML= "Reverse counting:";


document.getElementById("para").innerHTML=i;
}
</script>
</body>
</html>

Output:

7.4 for...in Loop


A for…in loop is used to loop through all the properties of an object. The syntax of a
for..in loop of JavaScript is mentioned below.

for (var variableName in objectName)


{

//code block to executed

If a program wants, the variable mentioned in the loop can be declared outside of the
loop. In each iteration of a for…in loop, one property of an object is assigned to the
variable. This loop continues until all the properties of the object are assigned to the
variable.

71 | P a g e
Let us understand the for…in loop with an example which is mentioned below.
<!DOCTYPE html>
<html>
<head>
<title>For in Loop</title>
</head>
<body>
<p id="para"></p>
<script>
var objStudent = { std:"VII", Roll_no:35, name:"Neha Sharma",
subject:"English", mark:65};
var report = "";
var varProperty;

for (varProperty in objStudent)


{
report += objStudent[varProperty] + "<br>";
}
document.getElementById("para").innerHTML=report;
</script>
</body>
</html>

7.5 for...of Loop


A for … of loop is used to loop through the value of iterable objects such as arrays,
strings, etc. The syntax of a for..of loop of JavaScript is mentioned below.

for (variableName of iterableObject) {


//code block to executed
}

Let us understand the for…of loop with an example which is mentioned below.
<!DOCTYPE html>
<html>
<head>
<title> For ... of Loop</title>
</head>
<body>

<script>
72 | P a g e
var instruments = ['keyboard','maracas','organ',
'pan flute','piano','recorder',
'saxophone','sitar','tambourine',
'triangle','trombone','trumpet',
'tuba','ukulele','violin','xylophone'];

var myvar;

for(myVar of instruments)
{
document.write(myVar +"<br>");
}
</script>

</body>
</html>

7.6 Label, break and continue statement


These three statements are used to control the flow of execution of a program more
precisely. These statements are very often implanted with nested loops. Nested Loop
means a loop inside another loop.

Here, pay attention to the fact that the label is not a keyword and it is just a label to
identify a statement or a block code. For more clarity study the following examples.

Example 1:
<html>
<head>
<title>Break and Label</title>
</head>
<body>
<script>
outerloop: // This is the name of label
for (var x= 0; x < 10; x++)
{
document.write("<br>Outerloop: " + x + "<br>");

innerloop:
for (var y= 0; y< 10; y++)
{
if (y > 4 ) break ; // Exit the innerloop
if (x == 3) break innerloop; // Exit the innerloop
73 | P a g e
if (x == 4) break outerloop; // Exit the outerloop
if (y == 5) break ; // Exit the innerloop
document.write("Innerloop: " + y + " <br>");
}
}
document.write("The outerloop has been breaked.");
</script>
</body>
</html>

If one analyses the output of this script by executing it in a web browser. The following
things can be understood with it.
1. A break statement is used to jump out of the loop. This means, once a break
statement is executed in a loop, the further execution of the loop is ceased.
2. A break statement with a label is used to jump out of any code block.

Example 2:
<html>
<body>
<script>
outerloop: // This is the label name
for (var x = 0; x < 5; x++)
{
document.write("<br> Outerloop: " + x + " <br>");

for (var y = 0; y < 5; y++)


{
if (x == 3)
{
continue outerloop; //It skips one iteration of the loop

}
document.write("Innerloop: " + y + " <br>");
}
}
</script>
</body>
</html>

If one analyses the output of this script by executing it in a web browser. The following
can be understood with it.
1. A continue statement is used to skip one loop iteration.

74 | P a g e
Lesson 8 : Clock & Counter
This lesson teaches how to make a clock and a counter on a web page using JavaScript.
Here, the first project is the clock and the second is a counter. Before starting these
projects, a programmer must understand a few prerequisites beforehand. Therefore this
lesson first discusses them.

8.1 Date object


There are various ways by which a current date and time can be obtained in the
JavaScript. In this section, the date object is being used in the lesson. The date object is
a data type in the JavaScript and it is used to get a range of time intervals for instance
years, months, days, hours, minutes, seconds, milliseconds, etc.

There are four ways by which it can be instantiated. However, this chapter focuses on
the only one that is given below.

var variableName = new Date();

Using the following methods a date object can provide the different duration of time.

Method Description
getDate() It provides the days as a number( from 1 to 31).
getDay() It provides week days as a number
getFullYear() It provides the year.
getMonth() It provides the month (from 0 to 11)
getHourse It provides the hour (from 0 to 23).
getMinutes() It gives the minutes (from 0 to 59)
getSeconds() It provides the seconds (from 0 to 59)
getMilliseconds() It gives the milliseconds (from o to 999)
getTime() It gives the time.

Let us understand these with the help of an example.


<!DOCTYPE html>
<html>
<head>
<title>Date Object</title>
</head>

75 | P a g e
<body>
<script>
// Instantiation of a date object
var myVar = new Date();

document.write("<br>Full year: "+ myVar.getFullYear());


document.write("<br>Month: "+ myVar.getMonth());
document.write("<br>Day: "+ myVar.getDay());
document.write("<br>Date: "+ myVar.getDate());
document.write("<br>Minutes: "+ myVar.getMinutes());
document.write("<br>Hours: "+ myVar.getHours());
document.write("<br>Seconds: "+ myVar.getSeconds());
document.write("<br>Milliseconds: "+ myVar.getMilliseconds());
document.write("<br>Time: "+ myVar.getTime());

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

Output:

8.2 setTimeout & setTimeInterval


There are several such situations when a programmer encounters a problem in which it
is required to call a function at a specific time in a program. Such time-bound calling of
a function in a program is referred to as scheduling a call.

In JavaScript, there are two such methods which facilitate this. They are mentioned
below.
 setTimeout: It calls a function once after an interval time (in milliseconds).

76 | P a g e
 setTimeInterval: It calls a function repeatedly after a fixed interval of time(in
milliseconds).

The syntax of these methods is given below.

window.setTimeout(myFunction, milliseconds);

window.setInterval(myFunction, milliseconds);

As can be seen, these functions require two parameters which are given as follows.
 myFunction: Any function which is required to be called after a time interval.
 milliseconds: It is a time period in milliseconds that indicates the time before the
process of a call takes place.

Let us understand these with the help of an example.

<!DOCTYPE html>
<html>
<head>
<title>setTimeout & setTimeInterval</title>
<script>

function myfunction()
{
setTimeout(myTimer1, 2000);
setInterval(myTimer2, 2500);
}
function myTimer1()
{
alert("Hello! How are you?");
}
function myTimer2()
{
document.getElementById("para").innerHTML
+= "<p>How may I assist you?</p>";
}
</script>
</head>
<body>
<h1>Click the following button and wait for a few seconds.</h1>
<button type="button" onclick="myfunction()">Click Me!</button>
<P id="para"></P>
</body>
</html>

77 | P a g e
In this program, the call of two functions is scheduled with the help of setTimeout() and
setTimeInterval(). In which, when a user clicks the button on the web page, then the
myTimer1() function is called after 2 seconds and writes some text on the web page.
Simultaneously, after 2.5 seconds from the button click event one more function
myTimer2() is called and it prints some text on the web page. The myTimer2() function is
constantly being called after every 2.5 seconds and each time it writes some text on the
web page.

8.3 Project 1 : Clock


Find all the code below.

<!DOCTYPE html>
<html>
<head>
<title>Clock</title>
</head>
<script>
function clock()
{
//Instantiation of date object
var dt = new Date();
hrs = dt.getHours();
mins = dt.getMinutes();
secs = dt.getSeconds();
ap ="AM";

//formatting of time
if (hrs > 11) { ap = "PM"; }
if (hrs > 12) { hrs = hrs - 12; }
if (hrs == 0) { hrs = 12; }
if (mins < 10) { mins = "0" + min; }
if (secs < 10) { s = "0" + secs; }

//Single to double digit


mins = addzero(mins);
secs = addzero(secs);

//display of time on the web page


document.getElementById("display").innerHTML
= hrs + ":" + mins + ":" + secs + " " + ap;

//to refreshers time on the web page after every


//500 milliseconds i.e. half second
setTimeout(clock, 500);
}

78 | P a g e
function addzero(num)
{
if (num<10){num = "0" + num}
return num;
}
</script>
<body onload="clock()">
<h1 id="display"></h1>
</body>
</html>

Output:

8.4 Project 2 : Counter

A counter is used to count the number of times an event or process takes place
somewhere. Commonly, it is used to count the number of people in various places, for
example, retail shops, shopping malls, etc. In places like that, it is very helpful to prevent
overcrowding and congestion.

This project is an attempt to design a counter on a web page, where one can keep a
record of the number of people present inside a hall (with limited seats) at one time.
This project should not only provide a facility to count up but also count down.

The code for such a counter on the web page is given below.

<!DOCTYPE html>
<html>
<head>
<title>Counter</title>
<style>
#counter{
font-family: "Lucida Console", Courier, monospace;
color:#329c9c;
font-size: 150px;
text-align: center;
}

79 | P a g e
button{
/* to make round edges*/
border-radius: 10px;
background-color:#44f5f5;
border-color:#44ffff ;
color: rgb(255, 255, 255);
font-size: xx-large;
}

table{
border: 5px dotted #44f5f5;
background-color: white;
}

body{
background-color: #44f5f5;
}

h2 {
color: white;
font-size: 50px;
}
</style>

<script>
var i =0;

function increment() {
i++;
display();
}

function decrement() {
i--;
display();
}

function display() {
document.getElementById("counter").innerHTML =i;
}
</script>

80 | P a g e
</head>
<body>
<h2 align ="center">COUNTER</h2>
<table border="1" cellspacing ="30px" align ="center">
<tr>
<td colspan="2" ><h1 id="counter">0</h1></td>
</tr>
<tr>
<td>
<button onclick="increment()">
Add Count
</button>
</td>
<td>
<button onclick="decrement()">
Lower Count
</button>
</td>
</tr>
</table>
</body>
</html>

Output:

81 | P a g e
Lesson 9 : Character counter & Calculator
This lesson demonstrates how to make a character (or letter) counter, a BMI calculator
and a calculator on a web page using JavaScript. Here, the first project is the character
counter, second is a BMI calculator and the third is a fully functional calculator. Before
starting these projects, a programmer must understand a few prerequisites beforehand.
Therefore this lesson first discusses them.

9.1 Project 1: Character counter

A character counter or letter counter is a tool whereby one can count the total number
of characters in a given text. One might wonder, why would somebody be wary about
the character count of a text? How exactly are such counters helpful?

The answers to such questions are very simple and straightforward, there many online
platforms that limit inputs to a certain number of characters. When a user exceeds such
a limit, then either the input is rejected or only part of it is accepted regardless of the
loss in the actual meaning of the input. Such online platforms include famous social
networking services such as Twitter, Facebook, Instagram, Linkedin, Pinterest, YouTube,
etc.

The code for such a character counter on the web page is given below.

<!DOCTYPE html>
<html>
<head>
<title>Character Counter</title>
</head>
<script>
function counter()
{
var text = document.getElementById("txt").value;
var charCount = text.length;
document.getElementById("para").innerHTML = "Total Character: ";
document.getElementById("count").innerHTML = charCount;

}
</script>
<style>

82 | P a g e
button{
/* to make round edges*/
border-radius: 12px;
background-color:#9b4135;
border-color:#8a382d ;
color: rgb(255, 255, 255);
font-size: x-large;
}

#count{
font-family:"Lucida Console";
color:#9b4135;
font-size: 75px;
text-align: center;
}

table{
border: 25px double #9b4135;
background-color: white;
text-align: center;
}

textarea {
/* sets size of the textarea */
height: 75px;
width: 400px;
}

h1 {
color: rgb(255, 255, 255);
line-height: 10px;
}

body{background-color: #9b4135;}

.lbl{color:#9b4135;}
</style>

<body>
<h1 align ="center">CHARACTER COUNTER</h1>

<table cellspacing ="30px" align ="center">


<tr><td>
83 | P a g e
<h2 class="lbl">
Type or Past the text below:
</h2>
<textarea id="txt"></textarea>
</td></tr>

<tr><td>
<button onclick="counter()">
Get the character count
</button>
</td></tr>

<tr><td>
<p id="para" class="lbl"></p>
<h1 id="count"></h1>
</td></tr>
</table>
</body>
</html>

9.2 Project 2: BMI Calculator


BMI stands for body mass index and it is a ratio which obtains from the height and
weight of a person. It is used to categorise a person in any one of the following
categories.
 Overweight: Greater than 24.9
 healthy weight: 18.6 and 24.9
 Underweight: Less than 18.6

The formula for calculating the BMI of a person is as follows.

Base on this formula, in this project, a BMI calculator is to be made on a web page.
Where a user provides height in centimetre and weight in kilogram. Upon the click of a
button, the calculated BMI displays on the web page. The code of such a BMI calculator
is provided below.

84 | P a g e
<!DOCTYPE html>
<html>
<head>
<title>BMI Calculator</title>
<style>
button{
/* to make round edges*/
border-radius: 10px;
background-color:#0a28cf;
border-color:#06104d ;
color: rgb(255, 255, 255);
font-size: x-large;
}
table{
border: 5px dashed #06104d;
background-color: white;
text-align: center;
}
body{background-color: #0a28cf;}
h1 {
color: rgb(255, 255, 255);
line-height: 10px;
}
</style>
<script>
function calculate()
{
var height = document.getElementById("height").value;
var weight = document.getElementById("weight").value;
var heightInMeter = height/100;

//the isNan() checks whether a value is an illegal number


if((height === '') || (height < 0) || (isNaN(height)))
{
window.alert("Please provide a valid height");

} else if (weight === '' || weight < 0 || isNaN(weight))


{
window.alert("Please provide a valid weight");
} else {
var BMI = weight / heightInMeter**2;
}

85 | P a g e
//round-up BMI figures up to two-digits only
BMI = BMI.toFixed(2)

document.getElementById("result").innerHTML = "Your BIM is " + BM


I;
}
</script>
</head>
<body>
<h1 align="center">BMI Calculator</h1>
<table cellspacing ="30px" align ="center"> <tr><td>

<p><label>Height in CM: </label><input type="text" id="height"></p>

<p><label>Weight in KG: </label><input type="text" id="weight"></p>


</td> </tr>
<tr><td>
<button onclick="calculate()">Calculate BMI</button>
</td> </tr>
<tr><td> <h2 id="result"></h2> </td> </tr>
<tr><td>
<h3>BMI (Body Mass Index) Weight Guide</h3>
<p>Overweight: Greater than 24.9</p>
<p>Healthy weight: 18.6 and 24.9</p>
<p>Under Weight: Less than 18.6</p>
</td> </tr> </table>
</body>
</html>

86 | P a g e
Output:

9.3 Eval() Method

An eval() method in JavaScript executes or evaluates an argument. An argument must


be in the JavaScript format and it should be enclosed within double-quotes. The syntax
is given below.

var variableName = eval ("argument");


For more clarity study the following example of this function.

<!DOCTYPE html>
<html>
<head>
<title>Eval() Function</title>
<script>

87 | P a g e
eval("alert('This argument is executed by eval()')");

var x = 50;
var y = 80;
var myVar1 = eval("x + y") + "<br>";
var myVar2 = eval("22 / 7") + "<br>";

document.write(myVar1);
document.write(myVar2);
</script>
</head>
<body>
</body>
</html>

Output:

9.4 Project 2: Calculator


Find all the code below.
</html>
<head>
<style>
.CalcuName{
margin-bottom: 10px;
text-align: center;
width: 542px;
font-size: 50px;
border-color:#0ceeee;
border-radius: 10px;
background-color: #1ae7ee;
}

input[type="button"]
{
/* to make edges round */
width:100%;
color: rgb(ff, ff, ff);

88 | P a g e
font-size:40px;
background-color:#9fe6f3;
border-radius: 10px;
border-color:#1ae7ee;
}

input[type="text"]
{
text-align: right;
font-size: 40px;
background-color: white;
border-radius: 10px;
border-color: black ;
width:100%
}
</style>

<script>
//function that displays numbers in the textbox
function display(num)
{
document.getElementById("txtbox").value+=num
}

//function that does calculations


function compute()
{
var problem = document.getElementById("txtbox").value
var solution = eval(problem)
document.getElementById("txtbox").value = solution
}

//function that clears number from the textbox


function txtClear()
{
document.getElementById("txtbox").value = ""
}
</script>
</head>

<body>
<div class = "CalcuName" >JavaScript Calculator</div>
<table>
<tr>
<td colspan="3"><input type="text" id="txtbox"/></td>
<td><input type="button" value="C" onclick="txtClear()"/> </td>
</tr>

<!-- buttons of different values-->


<tr>
<td><input type="button" value="1" onclick="display('1')"/> </td>
<td><input type="button" value="2" onclick="display('2')"/> </td>

89 | P a g e
<td><input type="button" value="3" onclick="display('3')"/> </td>
<td><input type="button" value="+" onclick="display('+')"/> </td>
</tr>

<tr>
<td><input type="button" value="4" onclick="display('4')"/> </td>
<td><input type="button" value="5" onclick="display('5')"/> </td>
<td><input type="button" value="6" onclick="display('6')"/> </td>
<td><input type="button" value="-" onclick="display('-')"/> </td>
</tr>

<tr>
<td><input type="button" value="7" onclick="display('7')"/> </td>
<td><input type="button" value="8" onclick="display('8')"/> </td>
<td><input type="button" value="9" onclick="display('9')"/> </td>
<td><input type="button" value="×" onclick="display('*')"/> </td>
</tr>

<tr>
<td><input type="button" value="." onclick="display('.')"/> </td>
<td><input type="button" value="0" onclick="display('0')"/> </td>
<td><input type="button" value="/" onclick="display('/')"/> </td>
<td><input type="button" value="=" onclick="compute()"/> </td>
</tr>
</table>
</body>
</html>

Output:

90 | P a g e

You might also like