[Go to site: main page, start]

0% found this document useful (0 votes)
23 views40 pages

JavaScript Basics: Introduction and Features

javascript basics

Uploaded by

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

JavaScript Basics: Introduction and Features

javascript basics

Uploaded by

Devraj Dhiman
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 4: JavaScript Part 1

CHAPTER 4
JavaScript Part 1
Topics Covered
4.1 Introduction to JavaScript
4.1.1 History of JavaScript
4.1.2 JavaScript as an Interpreted Language
4.1.3 Features of JavaScript
4.2 Prerequisites for Executing JavaScript Programs
4.3 Introduction to Script Tag
4.3.1 JavaScript Syntax and Rules
4.3.2 Common Errors
4.4 Input and Output from the Script
4.5 Data Types
4.6 Variables
4.7 Operators
4.7.1 Operators Precedence and Associativity
4.8 Inbuilt functions in JavaScript
4.9 Control of flow using Conditional Statements
4.10 Control of flow using Loops
4.1 Introduction to JavaScript
JavaScript is a computer programming language used to make websites and applications
dynamic and interactive. It is unique because it can run directly in your browser and also
on a server. Along with Hypertext Markup Language (HTML) and Cascading Style
Sheets (CSS), JavaScript is one of the most commonly used programming languages of
the Internet.
HTML provides the basic layout, structure, and content of a website. CSS provides
design, fonts, colors, effects, and other visual elements. JavaScript brings dynamism and
interactivity to the website. For example, pop-ups, animations, video and social media
embeds, drop-down menus, and many other website components are created using
JavaScript.

WEB APPLICATION 118


Chapter 4: JavaScript Part 1

4.1.1 History of JavaScript


JavaScript is developed in 1995 by Brendan Eich, a computer scientist and programmer
at Netscape Communications Corporation. The initial name of the JavaScript was
'Mocha'. After that, it changed to 'LiveScript', and then 'JavaScript'. Over the years,
JavaScript has evolved and become more powerful, with the addition of new features
such as object-oriented programming, regular expressions, and support for
asynchronous programming. Today, JavaScript is used in a wide range of applications,
including web development, mobile app development, and server-side programming.
JavaScript language is interpreted and executed by the browser.

4.1.2 JavaScript as an Interpreted Language


An interpreted language is one that does not require compiling into machine language.
It is executed by an interpreter that reads the source code and converts it into a form that
is directly executed. The interpreter executes the code line by line. Any error that is found
by the interpreter on any line of code, will stop the further execution of the program.
JavaScript is directly executed by the browser which interprets the program instruction
by instruction leading to slower execution of the program.

Static Website
A static website is a type of website that delivers the same content to all users. The
content is stored on the web server and is shown on the user’s browser as is, without any
change of content. Static websites are simple to create and host, and are typically used
for informational websites, such as brochure websites or portfolios. They don’t require
any server-side processing or database interactions, making them fast and easy to
maintain.

Dynamic Website

A dynamic website is a type of website that generates content based on user interactions
or other events. It generates custom content for each user based on their actions or
preferences. Dynamic websites are typically created using server-side programming
languages such as PHP, JavaScript, or Python, and they interact with a database to
retrieve and store data. Examples of dynamic websites include social media platforms,
e-commerce sites, and content management systems.

Static Website Dynamic Website

Content of Web pages cannot be changed Content of Web pages can be changed at
at runtime. runtime.

No interaction with the database possible. Interaction with database possible.

It is faster to load as compared to dynamic It is slower than a static website because it


websites as it is more text based. has images, audio & video content.

WEB APPLICATION 119


Chapter 4: JavaScript Part 1

Cheaper Development costs. More Development costs.

Blog Websites, Newsletter Contents, Facebook, MakemyTrip, TimesofIndia


Brochure websites

4.1.3 Features of JavaScript


1. Easy to Learn: JavaScript is easy to learn and the syntax of JavaScript is very
simple. A programming beginner can choose JavaScript as their first
programming language.
2. Case Sensitive: JavaScript is a highly case-sensitive programming language,
which means that the identifiers, keywords, variables, and function names must
be written correctly.
3. OS Support: It is supported by several operating systems including, Windows,
macOS, etc.
4. Control Statements: It has control statements like if, if-else, if-else-if, switch case,
and loop which helps users to write complex code using these control statements.
5. Client and Server-Side Support: Client-side or front-end web developers use
their programming talents to create visually appealing websites for users. This
means they build homepages, shopping pages, and slideshows. Server-side or
back-end developers create, design, and manage server-side code responsible for
data exchange. You can use JavaScript for both client-side and server-side
scripting. This means it’s helpful when designing website layouts and managing
server-side code for data exchange.
6. Object-Oriented: It is an object-oriented programming language, which means
that it uses objects to represent real-world entities and concepts.
7. Browser Support: All popular web browsers support JavaScript as they provide
built-in execution environments.
8. Functional Programming: In JavaScript, a function can be assigned to variables
just like any other data types. a function can accept another function as a
parameter and can also return a function. This provides you the ability to code in
functional programming style.
9. Dynamic: JavaScript is a high-level and dynamic programming language, which
means that the type of a variable is determined at runtime, rather than being
specified in the code.

Advantages of JavaScript
1. It is relatively easy to learn and use.
2. It can be used for client-side and server-side i.e. front end and back end.
3. It provides dynamism and interactivity on websites.
4. It runs on multiple platforms and devices. It is supported by all browsers.
5. There are many libraries, frameworks, and APIs available to facilitate tasks
6. It can create visually appealing web projects and to create drag & drop
components like sliders etc to make the website more professional.

WEB APPLICATION 120


Chapter 4: JavaScript Part 1

4.2 Prerequisites for Executing JavaScript Programs


The biggest advantage of JavaScript is that there is no need to purchase any tool to
develop the JavaScript application. These tools are freely available and can be easily
obtained.
A simple text editor like window notepad is required to create the JavaScript code. An
online text editor can be used alternatively. A HTML editor is another tool which can
edit the HTML source code and add the JavaScript code in the web page. An example of
an HTML editor is Dreamweaver which has lots of features and drag and drop facilities
to make the task easy. Microsoft Visual Web Developer Express is an advanced page
editor which can color the important JavaScript words and validate the code and load
the page into the web browser to view the changes or contents.

4.3 Introduction to Script Tag


JavaScript can be implemented using <script>… </script> tags. The <script> tag
containing JavaScript can be placed anywhere within the web page, but it is normally
recommended that it should be kept within the <head> tags. The <script> tag alerts the
browser program to start interpreting all the text between these tags as script commands.

The syntax of a JavaScript segment in HyperText Markup Language (HTML) is as


follows:
Since JavaScript is the default
<script language=”JavaScript” type=”text/JavaScript”> scripting language in HTML,
JavaScript code we can work within
</script> <script></script> tags.

The <SCRIPT> tag takes two important attributes:

1. Language- This attribute specifies the scripting language. Typically, its value will
be JavaScript. The recent versions of HTML have phased out the use of this
attribute and has become optional.
2. Type – This attribute is used to indicate the scripting language and its value
should be set to “text/JavaScript”. All current browsers are updated and are
JavaScript enabled by default. This attribute too is optional.

There are three different places in the HTML document where scripts can be used.

1. Body of the page: In this case when page is loaded in the browser then output is
displayed as the part of the HTML document.

WEB APPLICATION 121


Chapter 4: JavaScript Part 1

2. Header of the page: In this case code is written in the form of a function (groups
of JavaScript statements but treated as a single unit and referred to in the other
script in the same page).
3. As external file: In this case JavaScript code is written in another file having .js
extension. This file is included in a script tag by specifying the file name.

Writing first JavaScript program

<script>
[Link](“<i>hello World!</i>”);
// First JavaScript Program to print Hello World on the screen
</script>
Output on the browser : hello World!

1. Open any editor such as notepad and write the above program
2. Save the program with the .html extension in a proper folder or subfolder on a
drive like C:\JavaScript\myprograms.
3. Open the web browser like Google Chrome, I
4. Double Click the file you have created and saved in step 2, and then you can see
the output of your program.

4.3.1 JavaScript Syntax and Rules


JavaScript syntax is the set of rules that define a structured JavaScript. Here are some
tips to remember when writing your first JavaScript program.

1. Case Sensitivity: JavaScript is case sensitive i.e., uppercase letters and lower-case
letters have different meanings. For example, the word “alert” has a lowercase
“a”. so, if we type the word with an uppercase “A”, then the alert box will not be
displayed and the JavaScript code won't get executed.
2. Whitespace & Line Break: You can use spaces, tabs, and newlines anywhere in
the JavaScript Program. The JavaScript interpreter ignores them. Use tabs &
spaces to neatly format or indent your code. It makes the code easy to read &
understand.
3. Comments: The JavaScript allows us to add single line comments or Multi line
comments.
Single-line comments ( // ) − Any text between a // and the end of a line is
treated
as a comment.
<script>
//This program shows single line comments
</script>

Multi-line comments (/* */) − These comments may span multiple lines.

WEB APPLICATION 122


Chapter 4: JavaScript Part 1

<script>
/*This is an example of
multiline comment */
</script>

4.3.2 Common Errors


Since JavaScript is an interpreted language, there are some common mistakes that won’t
display the code correctly on your browser.
1. Missing quotation marks - [Link](“hello world)
2. Case sensitive - document -> cannot be written as Document
3. Missing parenthesis/brackets - [Link](“hello world”
4. Missing <script> tag in the program (either opening or closing)
5. Variable names misspelt.

Internal & External Java Script

Internal JavaScript: JavaScript can be added directly to the HTML file by writing
the code inside the <script> tag . We can place the <script> tag either inside
<head> or the <body> tag according to the need.

Example:

<html>
<head>
<title>Internal JavaScript</title>
</head>
<script>
/*Internal JavaScript*/
[Link]("Hello Friends!How are you?");
</script>
</html>

Output: Hello Friends! How are you?

External JavaScript: A JavaScript program can be written in a file and saved with
the .js extension. This file can be then linked inside the <HEAD> and </HEAD>
tags of the HTML document in which we want to add this code. The SRC attribute
of the <script> tag allows to give the path of the JavaScript file.

Example:
Open the text editor and type the following:

WEB APPLICATION 123


Chapter 4: JavaScript Part 1

document. write("Good Morning Friends!")

Save the above file as [Link]

Open another document in your text editor and type the following code:

<html>
<head>
<script src="[Link]">
</script>
</head>
</html>

Save the above file as [Link] and open it in your browser to see the output.
Output: Good Morning Friends!

4.4 Input and Output from the Script

1. [Link] method
JavaScript has access to the document property of the window object. The
document property returns the document object of the window which is being
used. When an HTML element is loaded onto the web browser then it becomes a
part of the document object. The document object is the root node of the HTML
page.
One can access the document object either by using [Link] or just
document. For example: [Link]() or [Link]()
The document object has a large range of properties or methods which a
developer can make use [Link] [Link]() in JavaScript helps to write a
JavaScript program or HTML expression into the document.

Example 1: We can write a string into a web page.


<html><head>
<script>
document. write("Beware of Cyber Scams")
</script>
</head></html>

Example 2: We can also write HTML content and display them on a web page.
<html><head>
<script>
[Link]("<b>Beware of Cyber
Scams<b>");</script>
</head></html>

WEB APPLICATION 124


Chapter 4: JavaScript Part 1

2. Dialog boxes

(i) alert() dialog box: An alert dialog box displays a short message or notification
to the user. Alert box gives only one button "OK" to select and proceed. It just
gives some information, necessary to the user and it can be invoked at various
events possible in JavaScript.

Example:
<html>
<head>
<title> JavaScript Alert Dialog Box
</title></head>
<body>
<script>
alert("You have chosen an Alert
box");
</script></body></html>

(ii) prompt() dialog box: The prompt dialog box is used to get some input from
the user. It has two buttons, one for “OK” and the other for “Cancel”. This method
returns the text entered in the input field when the user clicks the OK button. It
will return null if the user clicks the Cancel button. If the user clicks the OK button
without entering any text, an empty string is returned. For this reason, its result
is usually assigned to a variable when it is used. If you enter a number in the
prompt box, it will be stored as a string, as it always returns a string.

Example:
<html>
<head>
<script>
var yourname = prompt("Enter your name : ");
var age = prompt("Enter your age :");
[Link]("Your name is : " + yourname+"<br>");
[Link]("Your age is : " + age);
</script>
</head></html>

WEB APPLICATION 125


Chapter 4: JavaScript Part 1

(iii) confirm() dialog box: A confirmation dialog box is mostly used to take the
user's confirmation on any option. It displays a dialog box with two buttons: OK
and Cancel. If the user clicks on the OK button, it will return true. If the user clicks
on the Cancel button, it will return false. It returns a Boolean value depending on
whether the user clicks OK(true) or CANCEL(false) button.

Example:
<html>
<head>
<title> JavaScript Confirm Dialog Box </title></head>
<body>
<script>
var result = confirm("Are you sure you want to cancel the order?");
if(result==true)
{
[Link]("Order IS Canceled!");
}
else
{
[Link]("Order NOT Canceled");
}
</script></body></html>

3. Interacting with HTML


The HTML DOM (Document Object Model) provides a way to interact with and
manipulate the elements of an HTML document using JavaScript. It allows you
to access, modify, and add elements dynamically, change styles and classes,
handle events, and perform other operations on the document. One of the most

WEB APPLICATION 126


Chapter 4: JavaScript Part 1

common DOM functions you’ll use is the [Link]() function,


which returns the element with the ID you pass in as a parameter.

Output a value from JavaScript into an HTML element, in this case in the paragraph.

Example 1: This string is displayed in the


<html> paragraph with ID demo
<body>
<p>This example writes "Destination India!" into an HTML element</p>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "Destination India!";
</script> </body></html>

Example 2:
<html>
<head>
<script>
function myFunction()
{
[Link]("demo").innerHTML="Hello World";
}
</script>
</head>
<body>
<p>Click the button</p>
<button me</button>
<p id="demo"></p>
</body>
</html>

Output a value from an HTML form, in this case in a text box into an alert box in
JavaScript.

The value entered in this textbox


will be stored in a variable in JavaScript using
[Link]("myText").value

WEB APPLICATION 127


Chapter 4: JavaScript Part 1

<!DOCTYPE html>
<html>
<body>
Name: <input type="text" id="myText" value="Enter your full name here">
<button Here</button>

<script> Also see how the strings and


function myFunction() variable(along with spaces) are
{ concatenated with the + sign to get a
perfect message in the alert box
name=[Link]("myText").value
alert("Hello " + name +" Welcome to this page!")
}
</script>
</body>
</html>

4.5 Data Types


Data types in JavaScript define the data type that a variable can store. JavaScript supports
different data types .JavaScript includes Primitive and Non-Primitive data types. The
primitive data types in JavaScript include string, number, Boolean, undefined & null.
The non-primitive data type includes the object, array and functions.

Primitive Data Types

Numbers: A number data type can be an integer, a floating-point value, an exponential


value, a ‘NaN’ or a ‘Infinity’.

1. var a=250 // integer value


2. var b=25.5 // a number containing a decimal
3. var c = 10e4 // an exponential value which evaluates to 10*10000;

WEB APPLICATION 128


Chapter 4: JavaScript Part 1

There are special numeric values e.g. NaN and Infinity. If a number is divided by 0, the
resulting value is infinity.

1. 5/0; // results in infinity


2. The type of infinity is a number
3. typeof(infinity); // returns number

A ‘NaN’ results when we try to perform an operation on a number with a non-numeric value

1. ‘hi’ * 5; // returns NaN


2. typeof(NaN); // returns a number

String:
The string data type in JavaScript can be any group of characters enclosed by a single or
double-quotes or by backticks.

1. var str1 = “This is a string1”; // This is a string primitive type or string literal
2. var str2= ‘This is a string2’;
3. var str3 = `This is a string3`;

Boolean
The Boolean data type has only two values, true and false. It is mostly used to check a
logical condition. Thus Booleans are logical data types which can be used for comparison
of two variables or to check a condition. The true and false imply a ‘yes’ for ‘true’ and a
‘no’ for ‘false'. When we check the data type of ‘true’ or ‘false’ using typeof operator, it
returns a Boolean.

1. typeof(true) // returns Boolean


2. typeof(false) // returns Boolean

Let’s see an example of comparison statement:


var a =5;
var b=6;
a==b // returns false

WEB APPLICATION 129


Chapter 4: JavaScript Part 1

Undefined
Undefined data type means a variable that is not defined. The variable is declared but
doesn’t contain any value. In the following example, the variable ‘a’ has been declared
but hasn’t been assigned a value yet.

var a;
[Link](a) // This will return undefined.

Null
The Null in JavaScript is a data type that is represented by only one value, the ‘null’ itself.
A null value means no value.

var a = null;
[Link](a) // This returns null
typeof(a)

Non-Primitive Data Types


These types of data type are complex in nature which consist of more than one
component. Objects, arrays and functions are examples of composite data types. Object
contains properties and methods; array contains a sequential list of elements and
functions contains a collection of statements.

4.6 Variables
JavaScript variables are used to store data that can be changed later on. The variables can
be thought of as named containers. You can place data into these containers and then
refer to the data simply by naming the container. JavaScript variables must have unique
names. These names are called Identifiers.

Variable Naming Convention


JavaScript has some rules when we give the name to the variable. Following factor
must be considered while naming the variable.
1. Case Sensitivity: JavaScript variables are case sensitive. When name is given to
the variable then one must be careful to use the same case in the JavaScript
otherwise JavaScript considers it as a new variable and returns the error. For
example numvalue, Numvalue, numValue NUMVALUE are four different
variables.
2. Use Valid Characters: A variable must begin with underscore or letter only. All
other characters are invalid to start the variable name. Variables must not contain
blank spaces. For example, _numvalue, num2value, numvalue are valid names
while 2numvalue, _num value, num value are invalid names.
3. Avoid Reserved Words: Reserved words are the special words which have
specific meaning in JavaScript. These words cannot be used as a variable name.
For example ‘while’ is a reserved keyword hence cannot be used as a variable
name.

WEB APPLICATION 130


Chapter 4: JavaScript Part 1

Table: list of reserved keywords in JavaScript

Variable Declaration and Initialization


1. Variables in JavaScript can be defined using the keyword var (Note that var is the
keyword in JavaScript)
2. The equal to (=) sign is used to assign a value to a variable.
3. Users can either, separately declare the variable and then assign values to it or
straight-away declare and initialize the variables.
4. JavaScript variables can hold a value of any data type. For example, you can store
the value of number, string, Boolean, object, etc. data type values in JavaScript
variables.
5. The value type of a variable can change during the execution of a program and
JavaScript takes care of it automatically.

Examples of variables
var X; //defines a variable X, and by default no value is assigned to this variable
// the variable X has data type undefined

var y = 100; //defines a variable Y and assigns the integer value of 100 to it

var customer // declare the variable using the var keyword


customer=”Rose” //assigned a string to variable customer
var sum = x + y ; // sum is a variable that stores the sum of variables x and y
var check=true; //assigning a Boolean value

JavaScript Variable Scope

● Global Variables − A global variable has global scope which means it can be
defined anywhere in your JavaScript code.
● Local Variables − A local variable will be visible only within a function where it
is defined. Function parameters are always local to that function.

WEB APPLICATION 131


Chapter 4: JavaScript Part 1

JavaScript Literals
JavaScript Literals are the values that are assigned to a variable and depending on what
literal we assign to a variable its data type will be fixed.
For example:
var a= “Roman Numbers”
var b=45
var x=90.78
var c=[34,56,78]
var d=true

So a JavaScript Literal can be a numeric, string, floating-point value, an array , Boolean


value or even an object.

4.7 Operators
In JavaScript, an operator is a symbol that performs an operation on one or more
operands, such as variables or values, and returns a result. Let us take a simple
expression: 5 + 3 is equal to 8. Here 5 and 3 are called operands, and ‘+’ is called the
operator.

Some of the operators that JavaScript supports are:

● Arithmetic Operators
● Comparison (or Relational) Operators
● Logical Operators
● Assignment Operators

Arithmetic Operators
There are following arithmetic operators supported by JavaScript language: assume
variable a hold 10 and variable b holds 20 then:
Operator Description Example

+ (Addition) Adds two operands a + b will give 30

- (Subtraction) Subtracts second operand from the first a - b will give -10

* (Multiplication) Multiplies both operands a * b will give 200

/ (Division) Divides numerator by denominator. b / a will give 2

% (Modulus) Modulus operator gives the remainder b % a will give 0


after an integer division.

++ (Increment) Increment operator, increases integer a++ will give 11


value by one

WEB APPLICATION 132


Chapter 4: JavaScript Part 1

– (Decrement) Decrement operator, decreases integer a-- will give 9


value by one

** (Exponent) Can be used to give one value raised to a**2 will give 102 or
power another value. 100

Comparison Operators
These are some of the comparison operators supported by JavaScript language. Assume
variable has value 10 and variable b has value 20
Operator Description Example

== (Equal) Checks if the values of two operands are (a == b) is false


equal or not, if yes then the condition
becomes true.

!= (Not Equal) Checks if the values of two operands are (a != b) is true


equal or not, if values are not equal then the
condition becomes true.

> (Greater than) Checks if the value of the left operand is (a > b) is false
greater than the value of right operand, if
yes then the condition becomes true.

< (Less than) Checks if the value of the left operand is (a < b) is true
less than the value of the right operand, if
yes then the condition becomes true.

>= (Greater than Checks if the value of left operand is (a >= b) is false
or equal to) greater than or equal to the value of right
operand, if yes then the condition becomes
true.

<= (Less than or Checks if the value of left operand is less (a <= b) is true
equal to) than or equal to the value of right operand,
if yes then the condition becomes true.

Comparison statements always return or output a Boolean value, that is true or


false.
Logical Operators: These are some of the logical operators supported by JavaScript
language. Assume variable has value 10 and variable b has value 20 then:

Operator Description Example

&& (logical AND) If both the operands are non-zero (10&&20) will output 20

WEB APPLICATION 133


Chapter 4: JavaScript Part 1

numbers then and returns/outputs (20&&10) will output 10


the second number. For zero it (10>9&&7<6) will output
returns 0. false
In other cases it gives true only if (1<=5 && 2==2.0) will
both conditions are true otherwise output true
it gives false.

|| (logical OR) If both the operands are non-zero (10||20) will output 10
numbers then and returns/outputs (20||10) will output 20
the first number. If one of them is (45<=49||7<9) will
zero it returns the non-zero output true
number. (1>=5||2==2.7)will
In other cases it gives false only if output false
both conditions are false otherwise
it gives true.

! (logical NOT) It is used to reverse the logical state ! (10>9&&7<6) will


of its operand. if a condition is true output true
then logical not operator will make ! (45<=49||7<9) will
it false. output false

Assignment Operators: In JavaScript, an assignment operator is used to assign a value


to a variable.
Operator Description Example

= (Simple Assigns values from the right-side operand to z = x + y will assign


Assignment) the left side operand. the value of x + y
into z

+= (Add and It adds the right operand to the left operand z += x is equivalent
Assignment) and assigns the result to the left operand. to z = z + x

−= (Subtract It subtracts the right operand from the left z -= x is equivalent


and operand and assigns the result to the left to z = z - x
Assignment) operand.

*=(Multiply and It multiplies the right operand with the left z *= x is equivalent
Assignment) operand and assigns the result to the left to z = z * x
operand.

/= (Divide and It divides the left operand with the right z /= x is equivalent
Assignment) operand and assigns the result to the left to z = z / x
operand.

%= (Modules It takes modulus using two operands and z %= x is equivalent

WEB APPLICATION 134


Chapter 4: JavaScript Part 1

and assigns the result to the left operand. to z = z % x


Assignment)

Some important differences between Math and programming


• The "=" symbol represents equal to in Math but in programming, it means we are
assigning a value to a variable which will be stored in the memory to recall later.
• The left-hand side of the equal to sign is always a variable and the right-hand side may be
a number, a string, a variable or an expression.
x=10
y=6
x=x+1 //here x on the left side will be assigned value 10+1 that is 11
x=x + y //here x on the left side will be assigned value 11+6 that is 17
• The "==" symbol is used to compare something on the left side to the right side.

Conditional operator (? :)

The conditional operator is also called the ternary operator, containing the 3 parts. The
first part contains the condition and executes the second part if the condition evaluates
the true; Otherwise, it executes the third part.
Syntax
Condition ? First statement : Second statement
Parameters
● Condition − It is a conditional statement.
● First Statement − If the conditional statement evaluates true, First Statement will
be executed.
● Second Statement − If the conditional statement evaluates false, the Second
statement will be executed.
For example

status = (marks >= 30) ? "Pass" : "Fail"

The statement assigns value "Pass" to the variable status if marks are 30 or more.
Otherwise, it assigns the value of "Fail" to status.

typeof operator
typeof in JavaScript is an operator used for type checking and returns the data type of
the operand passed to it. The operand can be any variable, function, or object whose type
you want to find out using the typeof operator.

Syntax

typeof (operand)

WEB APPLICATION 135


Chapter 4: JavaScript Part 1

Here is the list of return values for the type of operator.

Some examples with Arithmetic operators

<!DOCTYPE html>
<html><body>
<h3>JavaScript Arithmetic Operators</h3>
<script>
var a=10;
var b=5
c=a+b;
[Link]("The value of a+b is: ", c)
[Link]("<br>")
c=a-b;
[Link]("The value of a-b is: ", c)
[Link]("<br>")
c=a*b;
[Link]("The value of a*b is: ", c)
[Link]("<br>")
c=a/b;
[Link]("The value of a/b is: ", c)
[Link]("<br>")
c=a%b; Observe how the increment
[Link]("The value of a%b is: ", c) operator written after the
[Link]("<br>") variable a will not increase the
value in place, it will be
[Link]("The value of a++ is: ", a++) reflected the next time variable
[Link]("<br>")
[Link]("The value of a++ is: ", a)
a is output.
[Link]("<br>")
[Link]("The value of ++a is: ", ++a)
However the increment or
[Link]("<br>")
decrement operator written
[Link]("The value of --b is: ", --b)
[Link]("<br>") before the variable will
</script> </body> increase or decrease the value
</html> in place.

WEB APPLICATION 136


Chapter 4: JavaScript Part 1

Increase reflected the next


time variable a is output.

The increment or decrement


reflected in place.

Some examples with Comparison/Relational operators


<!DOCTYPE html>
<html>
<body>
<h3>JavaScript Comparison Operators</h3>
<script>
var a;
a=10;
b=5;
[Link]("The value of a==b is: ", a==b)
[Link]("<br>")
[Link]("The value of a!=b is: ", a!=b)
[Link]("<br>")
[Link]("The value of a>b is: ", a>b)
[Link]("<br>")
[Link]('The value of 1=="1" is: ', 1=="1" )
[Link]("<br>")
[Link]('The value of 1==="1" is: ', 1==="1" )
[Link]("<br>")
</script>
</body>
</html>

WEB APPLICATION 137


Chapter 4: JavaScript Part 1

Some examples with Logical operators

Some examples with Assignment operators

<!DOCTYPE html>
<html>
<body>
<h3>JavaScript Assignment Operators</h3>
<script>
var a;
a=10;
a+=5;
[Link]("The value of a after a+=5 is: ", a)
[Link]("<br>")
a-=3
[Link]("The value of a after a-=2 is: ", a)
[Link]("<br>")
a*=5
[Link]("The value of a after a*=5 is: ", a)
[Link]("<br>")
a/=4
[Link]("The value of a after a/=4 is: ", a)
[Link]("<br>")
a**=2
[Link]("The value of a after a**=2 is: ", a)
[Link]("<br>")
</script>
</body>
</html>

WEB APPLICATION 138


Chapter 4: JavaScript Part 1

Operator Precedence & Associativity


Operator precedence: It ensures the priority of the operators to be executed when a
single expression contains multiple operators. So, whatever expressions have higher
priority, the compiler executes it first over other operators and then executes the
operators with the lower precedence.
Operator Associativity: It refers to the order in which an operator evaluates its operand
i.e. from left to right or right to left. When an expression has an operator with equal
precedence then association normally is left to right.
For example, the expression 6 + 3 * 10 / 2 will be written as ( 6 +( ( 3 * 10) / 2 ) ) and
operator will be evaluated from left to right.

Operator precedence and associativity in JavaScript


Operator Operator Use Operator Associativity Operator precedence

() Parenthesis Left to right 1


** Exponent Right to left 2
++ Increment Right to left
Highest to Lowest

-- Decrement Right to left 3


! Logical NOT Right to left
/ Division Left to right
* Multiplication Left to right 4
% Modulus Left to right
+ Addition Left to right
5
- Subtraction Left to right
Greater than, greater 6
>, >= Left to right
than or equal to
Less than, less than or
<, <= Left to right
equal to

WEB APPLICATION 139


Chapter 4: JavaScript Part 1

== Equality(comparison Left to right 7


!= Inequality Left to right
&& Logical AND Left to right 8
|| Logical OR Left to right 9
?: Conditional operator Left to right 10
= Assignment Right to left 11
*=, /=, Assignment according
%=, +=, - to the preceding Right to left 12
=, operator

4.8 Inbuilt functions in JavaScript

parseInt(): This function converts a string into an integer (a whole number) based on the
specified radix (base). The radix is optional, default is 10. If the first character of the string
cannot be converted to a number, it will return a NaN (Not a Number)
For example:
parseInt (“20”) returns 20
parseInt (“34.12”) returns 34
parseInt (“20 Pens”) returns 20
parseInt (“Pens 20”) returns NaN

parseFloat(): It accepts the string and converts it into a floating-point number. If the
string does not contain a numeral value or If the first character of the string is not a
Number, then it returns NaN.
For example:
parseFloat(“65”) returns 65
parseFloat(“65.33”) returns 65.33
parseFloat( “14 inch”) returns 14
parseFloat( “inch 14”) returns NaN

valueOf(): This method returns a number of a given variable.


For example:
var x =123;
[Link]() // will return 123;

var num=NaN
[Link]() // will return NaN

isNaN(): This method checks whether the passing argument is a number or not. It
returns true or false value as a result.
For example:
document. write(isNaN("Bottles")) //will return true

WEB APPLICATION 140


Chapter 4: JavaScript Part 1

document. write(isNaN(22)) //will return false


document. write(isNaN("13/12/2024")) //will return true
[Link](isNaN(-67)) //will return false

4.9 Control of Flow using Conditional Statements


Sometimes we need to write code which can take certain actions based on a variety of
scenarios. Control of Flow or Control Flow Structures is an important concept in
programming that allows you to run your code under different conditions or until a
certain condition is met.

Types of Control Statements in JavaScript:

● Conditional Statement: These statements are used for decision-making.


Decision-making statements evaluate the statements and control the program
flow depending upon the result of the condition provided.

● Iterative Statement: This is a statement that iterates repeatedly until a


condition is met. It executes the block of code repeatedly while some condition
evaluates to true. The execution of the set of instructions depends upon a
particular condition.

WEB APPLICATION 141


Chapter 4: JavaScript Part 1

Conditional Statements:
[Link] if..else statements: The if-else statement will perform some action for a specific
condition. If the condition is satisfied, then a particular code of action will be executed.
If the condition is not satisfied, it will execute another code of action that satisfies that
particular condition.

Example: If the hour is less than 18, create a "Good day" greeting, otherwise "Good
evening":
if (hour < 18)
{
greeting = "Good day";
}
else
{
greeting = "Good evening";
}

The else if statement can be used to specify a new condition if the first condition is false.
Example: If time is less than 10:00, create a "Good morning" greeting, if not, but time is
less than 20:00, create a "Good day" greeting, otherwise a "Good evening":
if (time < 10)
{
greeting = "Good morning";
}
else if (time < 20)
{
greeting = "Good day";
}
else
{
greeting = "Good evening";
}

WEB APPLICATION 142


Chapter 4: JavaScript Part 1

Example: Calculate discount price base on total amount. If the amount is less than 10000
then no discount. If the amount is less than 20000 then the discount is 5%. If the amount
is less than 30000 then the discount is 10%. If the amount is more than 30000 then the
discount is 15%.

Important Points to remember:


In the if-else if-else construct there can be only one if statement and one else statement but
there can be multiple else if statements. The else statement does not check a condition.
if(condition)
….statements…..
else if(condition)
….statements…..

else if(condition)
….statements…..

else if(condition)
….statements…..
else
….statements…..

WEB APPLICATION 143


Chapter 4: JavaScript Part 1

1. Using switch…case statement: The switch statement is used to select one of many
blocks of the code to be executed in a program. The switch expression is evaluated
once and the value of the expression is compared with the values of each case. If
a match is found, then the associated block of code is executed, otherwise the
default code block is executed.

Syntax:
● Expression is the value that you want to compare.
● Case value1, case value2, etc., represent the
possible values of the expression.
● break statement terminates the switch statement.
Without it, execution will continue into the next
case.
● Default specifies the code to run if none of the
cases match the expression.

Example: The following program asks the user to input the day of the week starting with
Sunday as 1. It displays the day as a string and displays a message for an invalid number.
<!DOCTYPE html>
<html><body>
<h2>Displaying the Day of the Week</h2>
<p id="demo"></p>
<script>
var day;
var daynum=prompt("Enter the Day of the Week (Sunday-1)")
switch(daynum) {
case 1:
day = "Sunday";
break;
case 2:
day = "Monday";
break;

WEB APPLICATION 144


Chapter 4: JavaScript Part 1

case 3:
day = "Tuesday";
break;
case 4:
day = "Wednesday";
break;
case 5:
day = "Thursday";
break;
case 6:
day = "Friday";
break;
case 7:
day = "Saturday";
break;
default:
[Link]("Invalid Number")
}
[Link]("demo").innerHTML = "Today is " + day;
</script></body></html>

Example: Based on the grade entered show the remark as per the student grade
<!DOCTYPE html>
<html> <body>
<script>
var grade=prompt("Enter the grade A/B/C");
switch(grade)
{ case 'A':
result="Excellent"
break;
case 'B':
result="Very Good"
break;
case 'C':
result="Good"
break;
default:
result="No Grade"
}
[Link](result);
</script>
</body> </html>

WEB APPLICATION 145


Chapter 4: JavaScript Part 1

4.10 Control of Flow using Loops


Iterative Statements: These statements repeat a set of instructions for a certain number
of times. These statements are also called looping statements or loops. A loop has 3 parts
as explained below:

● Initialization: Initializes a counter variable to start the loop. This is done only
once in a loop.
● Condition: Specifies a condition that must evaluate to true for the next iteration.
If the condition evaluates to true, the statements inside the loop body will execute,
If the condition evaluates to false, the loop will terminate.
● Iteration: Increase or decrease the counter variable after every pass of the loop.

1. for loop: The for loop is used to repeat the set of instructions for a fixed number
of times. The syntax to use the for loop is as follows:

for (Initialization; condition; iteration)

//set of JavaScript statements

WEB APPLICATION 146


Chapter 4: JavaScript Part 1

Example: To display the text “Hello Life! You are so Good” for 5 times

<html>
<body>
<p> For loop Example</p>
<script>
for (i = 0; i < 5; i++) {
[Link]("Hello Life! You are so Good" +"<br>"); }
</script>
</body>
</html>

Output

Example: A program to display numbers from 0 to 10

<html>
<body>
<p> For loop Example 2</p>
<script>
for (i = 0; i <=10; i++) {
[Link](i +"<br>"); }
</script>
</body>
</html>

Output:

WEB APPLICATION 147


Chapter 4: JavaScript Part 1

2. while loop: The while loop is also used to repeat a set of instructions until a
conditional statement returns true. Once the condition returns false, the loop is
terminated. The syntax to use the while loop is as follows:

Initialization;
while (condition)
{ Why while loops?
//set of JavaScript statements In advanced programming while
iteration; loops are used when we may not
} have a fixed number of iterations.
For example in a video game we
want the user click a certain key to
end the game, we can use a while
loop to make the game go on and it
will break only if that key is pressed.
In for loops the number of iterations
is mostly fixed.

Example: A program to display the square of numbers between 1 to 5


Output:
<html>
<body>
<p> While loop Example 1</p>
<script>
var i=1
while (i<=5)
{
var square= i * i;
[Link]("Square of "+i+" "+square"<br>");
i++;
}
</script> </body> </html>

WEB APPLICATION 148


Chapter 4: JavaScript Part 1

Example: The same example of for Loop can be executed with the use of while loop

<html>
<body>
<p> While loop Example 2</p>
<script>
var i=1
while (i<=5)
{
[Link]("Hello Life! You are so Good" +"<br>");
i++;
}
</script>
</body>
</html>

Use of break and continue statements in loops


The break statement can be used within a loop to stop execution based on a condition
being true. Since the loop is stopped, the statements after the loop will follow.

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Loops</h2> Output:
<p>A loop with a <b>break</b> statement.</p>
<p id="demo"></p>
<script>
var text = "";
for (var i = 0; i < 10; i++)
{
if (i === 3)
{
break;
}
text += "The number is " + i + "<br>"; The loop stops as soon
}
as i becomes equal to 3
[Link]("demo").innerHTML = text;
</script>
</body>
</html>

The continue statement is used with a loop to ignore execution when a condition is true.
This statement will not stop the execution of the rest of the loop.

WEB APPLICATION 149


Chapter 4: JavaScript Part 1

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Loops</h2>

<p>A loop with a <b>continue</b> statement.</p>


<p>A loop which will skip the step where i = 3.</p>
<p id="demo"></p>
<script>
var text = "";
for (var i = 0; i < 10; i++)
{
if (i === 3)
{
continue;
}
text += "The number is " + i + "<br>";
}
[Link]("demo").innerHTML = text;
</script>
</body>
</html>

The output for 3 is missing

WEB APPLICATION 150


Chapter 4: JavaScript Part 1

Exercise

I. Multiple Choice Questions

1. Which of the following keywords is used to initialize variables in JavaScript?


a. for
b. getElement
c. var
d. Boolean

2. _______________ can provide the information to the user or ask him to input the
value required by a program.
a. Browser
b. Dialog box
c. Value box
d. Window box

3. A multiline comment in JavaScript is written as:


a. /* Welcome to JavaScript
b. // Welcome to JavaScript
c. / Welcome to JavaScript
d. /* Welcome to JavaScript */

4. JavaScript is an __________ computer programming language.


a. Interpreted
b. Compiler
c. Assembler
d. None of the above

5. _________ is used to convert string to integer value.


a. Integer()
b. ParseInt()
c. parseInt()
d. Stringtoinit()
6. What will be the output of the following JavaScript code?
var s= “welcome”;
var x=30;
alert(s+x);
a. welcome 30
b. welcome30
c. welcome
d. 30
7. What are the three important parts in a for loop in JavaScript?
a. initialization; assignment; increment

WEB APPLICATION 151


Chapter 4: JavaScript Part 1

b. initialization; condition; increment


c. initialization; increment; condition
d. condition; increment; initialization
8. When a variable is declared without assigning value then it contains the
__________ value which may cause the runtime error.
a. Null
b. Zero
c. Undefined
d. New
9. A _______________ is a set of statements enclosed in braces as a single statement.
a. block
b. expression
c. box
d. sequence
10. <script> tag can be inserted in the:
a. Head section
b. Body section
c. Both a & b
d. None of these

11. An alternative to an if..else statement is:


a. loop
b. conditional operator
c. typeof operator
d. arithmetic operator
12. An external JavaScript file will have the extension as:
a. .html
b. .JavaScript
c. .jc
d. .js

13. If a number is divided by 0, the resulting value is _____________..


a. zero
b. infinity
c. null
d. none of the above
14. The output of the following will be:
[Link]("english"*75);
a. infinity
b. english75
c. NaN
d. english*75
15. ____________statement terminates the switch statement, without which the
execution will continue into the next case.

WEB APPLICATION 152


Chapter 4: JavaScript Part 1

a. end
b. break
c. stop
d. continue
16. In the switch..case statement,____________ specifies the code to run if none of the
cases match the expression.
a. omit
b. skip
c. fail
d. default
17. Which of the following is not a valid variable name?
a. grade_pay
b. 2gradepay
c. gradepay
d. GradePay
18. Which of the following was also the name of JavaScript?
a. LiveScript
b. VBscript
c. BasicScript
d. None of the above
19. There can be only one if statement in if-else if-else construct.
a. True
b. False

20. _____________ operator and gives the remainder of after an integer division.
a. /
b. %
c. &&
d. <=

II. Find the Output of the following code snippets:


i) 21 + 10 ** 2 / 4 – 45
ii) !(true || false && true)
iii) 15%7+10<19%8+6*2

var x=17,y=12;
x--;
iv) x+=10;
y+=x
y++
[Link](y)

WEB APPLICATION 153


Chapter 4: JavaScript Part 1

v) <!DOCTYPE html>
<html>
<body>
<p> While loop</p>
<script>
var i=1;
while(i<= 5)
{
if( i==3)
continue
i++
[Link]("The number is " + i+ "<br>");
}
</script>
</body>
</html>

vi) <script>
for (i-0; i<5; i++)
{
[Link](“@” + “<br>”);
}
</script>

vii)
var i=10;
var j=2;
while(i > j)
{
i = i / j;
[Link](i+” “);
}

III. Very Short Answer Questions


1. Who developed JavaScript? What was the initial name of JavaScript?
2. Why is JavaScript called an Interpreted language?
3. Write any 3 advantages of JavaScript
4. What are the tools required to write and view a JavaScript program?
5. What is meant by "External JavaScript file"?
6. What are the types of comments in JavaScript?
7. List the common errors that are usually made in a JavaScript program.
8. What are Data types?
9. Which are the non-primitive data types?

WEB APPLICATION 154


Chapter 4: JavaScript Part 1

10. What are variables? Declare a variable subject and give it a value as “Web
Application”.
11. Differentiate between local and global variables.
12. What are different types of operators in JavaScript?
13. What is the use of typeof operator?
14. What is the difference between operator precedence and associativity?
15. Differentiate between conditional statements and iterative statements.
IV. Short Answer Questions
1. Differentiate between a static and dynamic website.
2. Explain any 4 features of JavaScript.
3. Explain the tag used to write a JavaScript program? Write about its attributes also.
4. Explain the [Link] method
5. Differentiate between the alert(), prompt() and confirm() dialog boxes.
6. Explain the primitive data types of JavaScript.
7. What are the rules for naming the variables?
8. Explain the conditional operator with an example.

V. Write the JavaScript program for the following:


1. Write a program to print numbers from 1 to 20.
2. Write a program to print numbers from 1 to 20 in reverse order.
3. Write a program to print sum of numbers between 1 to 20
4. Write a program to find if the number entered by the user is even or odd.
5. Write a program to find the sum of all even and odd numbers between 1 to 50.
6. Write a program to calculate the area of a triangle. Formula: (base/height)/2
7. Write a program to accept a number from the user. Based on the choice ‘S’ or ‘C’
entered by the user, calculate and display:
i. Square of the number
ii. Cube of the number
8. Write a program to accept 2 numbers from the user and calculate the area of a
rectangle and square.
i. Area of rectangle = length & breadth
ii. Area of square = side * side
9. Write a program to check if a number entered is positive, negative or zero.
10. Accept 3 numbers from the user and write a program to find the largest/smallest
of 3 numbers
11. Write a program to display a multiplication table for a number.
12. Write a program to find the area and circumference of a circle. (pi = 3.14)
i. Area of circle = 2 * pi * r
ii. Circumference of circle = pi * r * r
13. Write a program to find the factorial of a number entered by the user.
14. Use the loop to print the numbers 8,11,14,17,20, . . . ,83,86,89
15. Write a program to accept salary and grade from the user. Based on the grade add
the bonus to the salary and display net salary

WEB APPLICATION 155


Chapter 4: JavaScript Part 1

Grade Bonus
A 30% of salary
B 35% of salary
C 20% of salary
D 15% of salary

16. Calculate discount price base on total amount. If the amount is less than 10000
then no discount. If the amount is less than 20000 then the discount is 5%. If the
amount is less than 30000 then the discount is 10%. If the amount is more than
30000 then the discount is 15%.

VI. Answer the following questions


1. Amit has written the following code in JavaScript, but it is not getting displayed on
the browser. He is not able to find the errors in his program. Find the errors in the
following code and rewrite the correct code:

<script>
var prod, counter;
prod=2;
ctr =2;
while (ctr<=9)
prod= prod * ctr;
ctr = ctr+2;
[Link](prod + “, “+ ctr +”<br>”);
}
2. Give the JavaScript statement for each of the following:
a. A variable ‘sum’ that stores the sum of variables ‘A’ & ‘B’
b. To print the data type of variable ‘k’
c. To take ‘age’ as input from the user

3. Rohit, a student of class 12, is learning JavaScript. During examination, he has been
assigned an incomplete JavaScript code (shown below). Help him in completing the
code :

Incomplete Code

var bs=______________(prompt("Enter salary")); --------- line 1


var da,hra,gs;
if(bs>=10000 ______ bs<=20000) ---------- line 2
{
da=bs*15/100;
hra=bs*10/100;
}
________ (bs>=20001 && bs<=30000) ----------- line 3

WEB APPLICATION 156


Chapter 4: JavaScript Part 1

{
da=bs*12/100;
hra=bs*8/100;
}
else if(bs>=30000)
{
da=bs*10/100;
hra=bs*6/100;
}
gs=bs+da+hra;
______________(gs); ------------ line 4

4. The following program is given using if...else if. Use the same program to convert
using switch..case without changing the meaning of the program:
<script>
var grade=parseInt(prompt(“Enter grade of employee”))
if (grade==”A”)
[Link](“You are Vice President”)
else if(grade==”B”)
[Link](“You are LEVEL 1 Officer”)
else if(grade==”C”)
[Link](“You are a Trainee”)
else
[Link](“You are not employed”)
</script>

WEB APPLICATION 157

You might also like