0% found this document useful (0 votes)
3 views

3 JAVASCRIPT (Unit 3)_380629ce76217ebcb335068efe6aa9ae_1

JavaScript is a scripting language developed to add interactivity to HTML pages, allowing for dynamic content and event-driven programming. It can be embedded directly in HTML or linked as an external file, and is supported by all major browsers. Key features include the ability to manipulate HTML elements, respond to user events, and utilize various data types and operators.

Uploaded by

Tanisha Gupta
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)
3 views

3 JAVASCRIPT (Unit 3)_380629ce76217ebcb335068efe6aa9ae_1

JavaScript is a scripting language developed to add interactivity to HTML pages, allowing for dynamic content and event-driven programming. It can be embedded directly in HTML or linked as an external file, and is supported by all major browsers. Key features include the ability to manipulate HTML elements, respond to user events, and utilize various data types and operators.

Uploaded by

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

JAVASCRIPT

Parul Saxena, MITS 1


• To add interactivity to HTML inside the browser itself,
the technology of JavaScript was developed.
• JavaScript involves programming. We can write small
programs that execute inside the HTML page, based on
certain events.
• JavaScript is an interpreted language. It can be directly
embedded inside HTML pages, or it can be kept in a
separate file (with extension .js) and included in the
HTML page.
• It is supported by all the major browsers, such as
Internet Explorer, Firefox and Netscape Navigator.

Parul Saxena, MITS 2


JavaScript has several features:
• Programming tool: JavaScript is a scripting language with a very simple
syntax.
• Can produce dynamic text into an HTML page: for example, the
JavaScript statement document.write(“<h1>” + name + “</h1>”);
results into the HTML output
<h1> Ram </h1>, if the variable name contains the text Ram.
• Reacting to events: JavaScript code executes when something happens,
like when a page has finished loading or when a user clicks on an HTML
element.
• Read and write HTML elements: JavaScript can read and change the
content of an HTML element.

Parul Saxena, MITS 3


<html>
<body>
<script>
document.write(“Hello World!”);
</script>
</body>
</html>

document is the name of an object.


write is a method of that object.

Parul Saxena, MITS 4


• Scripts that we want to execute only when they are called, or
when an event is triggered, go in the head section. That is, it
does not execute on its own.
• If we put scripts in the body section, then they automatically
get executed when the page loads in the browser. Fig 7.2

Parul Saxena, MITS 5


• JavaScript can "display" data in different ways:
– Writing into an HTML element, using innerHTML.
– Writing into the HTML output using document.write().
– Writing into an alert box, using window.alert().
– Writing into the browser console, using console.log().

Parul Saxena, MITS 6


Using innerHTML
• To access an HTML element, JavaScript can use
the document.getElementById(id) method.
• The id attribute defines the HTML element. The innerHTML property defines the
HTML content:
• Example
• <html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>

Parul Saxena, MITS 7


Using document.write()

• For testing purposes, it is convenient to use document.write():


• Example
• <!DOCTYPE html>
<html>
<body>
<h1>My First Web Page1</h1>
<p>My first paragraph1.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>

Parul Saxena, MITS 8


Using document.write() after an HTML document is
loaded, will delete all existing HTML:

<html>
<body>

<h2>My First Web Page</h2>


<p>My first paragraph.</p>

<button type="button" onclick="document.write(5 +


6)">Try it</button>

</body>
</html>
Parul Saxena, MITS 9
Using window.alert()

• You can use an alert box to display data:


<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
alert(5 + 6);
</script>
</body>
</html>
Parul Saxena, MITS 10
Using console.log()
• For debugging purposes, you can call the console.log() method in
the browser to display data.
• The console.log() method writes a message to the console.
• The console is useful for testing purposes.
• Tip: When testing this method, be sure to have the console view
visible (press F12 to view the console).

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

Parul Saxena, MITS 11


Variables
• Variables are declared using the keyword var. However, this
keyword is optional.
• var name = “test”; OR name = test;
• Variables can be local or global
– Local variables: When we declare a variable within a function, the
variable can only be accessed within that function. When we exit the
function, the variable is destroyed. This type of variable is a local
variable.
– Global variables: If we declare a variable outside a function, all the
functions on HTML page can access it. The lifetime of these
variables starts when they are declared and ends when the page is
closed.

Parul Saxena, MITS 12


JavaScript Statements
• Example
var x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
• JavaScript Programs
– A computer program is a list of "instructions" to be "executed" by a computer.
– In a programming language, these programming instructions are called statements.
– A JavaScript program is a list of programming statements.
• JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.

document.getElementById("demo").innerHTML = "Hello John.“

• JavaScript programs (and JavaScript statements) are often called


JavaScript code.
Parul Saxena, MITS 13
Semicolons ;
• Semicolons separate JavaScript statements.
• Add a semicolon at the end of each executable
statement:
• var a, b, c; // Declare 3 variables
a = 5; // Assign the value 5 to a
b = 6; // Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c
• When separated by semicolons, multiple
statements on one line are allowed:
a = 5; b = 6; c = a + b;

Parul Saxena, MITS 14


JavaScript Code Blocks

• JavaScript statements can be grouped together in code blocks,


inside curly brackets {...}.
• The purpose of code blocks is to define statements to be
executed together.
• One place you will find statements grouped together in blocks,
is in JavaScript functions:
• function myFunction() {
document.getElementById("demo1").innerHTML = "Hello John!";
document.getElementById("demo2").innerHTML = "How are
you?";
}

Parul Saxena, MITS 15


JavaScript Keywords

• Keyword Description
• Break Terminates a switch or a loop
• Continue Jumps out of a loop and starts at the top
• do ... While Executes a block of statements, and repeats
the block, while a condition is true
• For Marks a block of statements to be executed, as
long as a condition is true
• Function Declares a function
• if ... Else Marks a block of statements to be executed,
depending on a condition
• Return Exits a function
• Switch Marks a block of statements to be executed,
depending on different cases
• try ... Catch Implements error handling to a block of
statements
• var Declares a variable

Parul Saxena, MITS 16


JavaScript syntax
• JavaScript syntax is the set of rules, how JavaScript programs are constructed:
– var x, y, z; // How to declare variables
x = 5; y = 6; // How to assign values
z = x + y; // How to compute values
• JavaScript Values
– The JavaScript syntax defines two types of values: Fixed values and variable values.
– Fixed values are called literals. Variable values are called variables.
• JavaScript Literals
– The most important rules for writing fixed values are:
– Numbers are written with or without decimals: 10.50, 1001
– Strings are text, written within double or single quotes: "John Doe“ or 'John Doe‘
• JavaScript Variables
– In a programming language, variables are used to store data values.
– JavaScript uses the var keyword to declare variables.
– An equal sign is used to assign values to variables.
– In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
– var x; x = 6;

Parul Saxena, MITS 17


<html>
<body>

<h2>JavaScript Variables</h2>

<p>In this example, x is defined as a variable.


Then, x is assigned the value of 6:</p>

<p id="demo"></p>

<script>
var x;
x = 6;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Parul Saxena, MITS 18


JavaScript Operators
• JavaScript uses arithmetic operators ( + - * / )
to compute values:
(5 + 6) * 10
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = (5 + 6) * 10;
</script>
• JavaScript uses an assignment operator ( = ) to assign values to
variables:
var x, y;
x = 5;
y = 6;

Parul Saxena, MITS 19


JavaScript Comments

• Not all JavaScript statements are "executed".


• Code after double slashes // or between /* and */ is
treated as a comment.
• Comments are ignored, and will not be executed:
• var x = 5; // This will execute
// var x = 6; This will NOT execute
• Multi-line Comments
– Multi-line comments start with /* and end with */.
– Any text between /* and */ will be ignored by JavaScript.

Parul Saxena, MITS 20


• JavaScript is Case Sensitive
• All JavaScript identifiers are case sensitive.
• The variables lastName and lastname, are two
different variables:
• var lastname, lastName;
lastName = "Doe";
lastname = "Peterson";

Parul Saxena, MITS 21


JavaScript Identifiers

• All JavaScript variables must be identified with unique


names.
• These unique names are called identifiers.
• Identifiers can be short names (like x and y) or more
descriptive names (age, sum, totalVolume).
• The general rules for constructing names for variables
(unique identifiers) are:
– Names can contain letters, digits, underscores, and dollar signs.
– Names must begin with a letter
– Names are case sensitive (y and Y are different variables)
– Reserved words (like JavaScript keywords) cannot be used as
names

Parul Saxena, MITS 22


JavaScript Data Types

• JavaScript variables can hold numbers like 100 and text


values like "John".
• In programming, text values are called text strings.
• JavaScript can handle many types of data, but for now, just
think of numbers and strings.
• Strings are written inside double or single quotes. Numbers
are written without quotes.
• If you put a number in quotes, it will be treated as a text
string.
• Example
var pi = 3.14;
var person = "John";
var answer = 'Yes I am!';
Parul Saxena, MITS 23
JavaScript Arithmetic Operators

• Arithmetic operators are used to perform arithmetic on


numbers:
• Operator Description
• + Addition
• - Subtraction
• * Multiplication
• / Division
• % Modulus (Division Remainder)
• ++ Increment
• -- Decrement
Parul Saxena, MITS 24
JavaScript Assignment Operators

• Assignment operators assign values to JavaScript


variables.
• Operator Example Same As
• = 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%y
Parul Saxena, MITS 25
JavaScript String Operators

• The + operator can also be used to add


(concatenate) strings.
• Example
• var txt1 = "John";
var txt2 = “Roy";
var txt3 = txt1 + " " + txt2;
• The result of txt3 will be:
John Roy
Parul Saxena, MITS 26
JavaScript String Operators

• The += assignment operator can also be used


to add (concatenate) strings:
• Example
var txt1 = "What a very ";
txt1 += "nice day";
• The result of txt1 will be:
What a very nice day

Parul Saxena, MITS 27


• var x = 5 + 5;
var y = "5" + 5;
var z = "Hello" + 5;
• var $ = 2;
var $myMoney = 5;
document.getElementById("demo").innerHTML = $ + $myMoney;

Parul Saxena, MITS 28


The ** Operator

<html>
<body>

<h2>The ** Operator</h2>

<p id="demo"></p>

<script>
var x = 5;
document.getElementById("demo").innerHTML = x ** 2;
</script>

</body>
</html>

//x ** y produces the same result as Math.pow(x,y):

Parul Saxena, MITS 29


JavaScript Data Types

• JavaScript variables can hold many data types:


numbers, strings, objects and more:
• var length = 16; // Number
var lastName = "Johnson"; // String
var x = {firstName:"John", lastName:"Doe"};
// Object
• This code assigns many values (John, Doe) to
a variable named x

Parul Saxena, MITS 30


• var x = 16 + "Volvo";
//16Volvo
• var x = 16 + 4 + "Volvo";
//20Volvo
• var x = "Volvo" + 16 + 4;
//Volvo164

• In the first and second example, JavaScript treats


16 and 4 as numbers, until it reaches "Volvo".
• In the third example, since the first operand is a
string, all operands are treated as strings
Parul Saxena, MITS 31
JavaScript Types are Dynamic
• JavaScript has dynamic types. This means that
the same variable can be used to hold
different data types:
• Example
• var x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String

Parul Saxena, MITS 32


<html>
<body>

<h2>My First JavaScript</h2>

<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>

<p id="demo"></p>

</body>
</html>

Parul Saxena, MITS 33


JavaScript Can Change HTML Content
• One of many JavaScript HTML methods is getElementById().
• The example below "finds" an HTML element (with id="demo"), and changes the element
content (innerHTML) to "Hello JavaScript":

<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello


JavaScript!“'>Click Me!</button>

</body>
</html> //js6.html

Parul Saxena, MITS 34


JavaScript Can Change HTML Attribute Values
• In this example JavaScript changes the value of the src (source) attribute of an <img> tag:
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p>JavaScript can change HTML attribute values.</p>

<p>In this case JavaScript changes the value of the src (source) attribute of an image.</p>

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the


light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the


light</button>

</body>
</html>

// js7.html
Parul Saxena, MITS 35
JavaScript Can Change HTML Styles (CSS)
• Changing the style of an HTML element, is a variant of changing an HTML
attribute:
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change the style of an HTML element.</p>

<button type="button"
onclick="document.getElementById('demo').style.fontSize='35px'">Click
Me!</button>

</body>
</html>

Parul Saxena, MITS 36


JavaScript Can Hide HTML Elements
• Hiding HTML elements can be done by changing the display style:
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can hide HTML elements.</p>

<button type="button" onclick="document.getElementById('demo').style.display='none'">Click


Me!</button>

</body>
</html>

Parul Saxena, MITS 37


JavaScript Can Show HTML Elements
• Showing hidden HTML elements can also be done by changing the display style:
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p>JavaScript can show hidden HTML elements.</p>

<p id="demo" style="display:none">Hello JavaScript!</p>

<button type="button" onclick="document.getElementById('demo').style.display='block'">Click


Me!</button>

</body>
</html>

Parul Saxena, MITS 38


The <script> Tag
• In HTML, JavaScript code is inserted
between <script> and </script> tags.
<html>
<body>

<h2>JavaScript in Body</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML="My First JavaScript";
</script>

</body>
</html>

Parul Saxena, MITS 39


• JavaScript Functions and Events
– A JavaScript function is a block of JavaScript code, that
can be executed when "called" for.
– For example, a function can be called when
an event occurs, like when the user clicks a button.
• JavaScript in <head> or <body>
– We can place any number of scripts in an HTML document.
– Scripts can be placed in the <body>, or in
the <head> section of an HTML page, or in both.

Parul Saxena, MITS 40


JavaScript in <head>
• In this example, a JavaScript function is placed in the <head> section of an HTML page.
• The function is invoked (called) when a button is clicked:
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>

<h2>JavaScript in Head</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>
Parul Saxena, MITS 41
JavaScript in <body>
• In this example, a JavaScript function is placed in the <body> section of an
HTML page.
• The function is invoked (called) when a button is clicked:
<html>
<body>

<h2>JavaScript in Body</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>

</body>
</html> Parul Saxena, MITS 42
External JavaScript
• Scripts can also be placed in external files:
• External file: myScript.js
• function myFunction() {
document.getElementById("demo").innerHTML = "Para
graph changed.";
}
• JavaScript files have the file extension .js.
• To use an external script, put the name of the script file in
the src (source) attribute of a <script> tag:
• Example
• <script src="myScript.js"></script>

Parul Saxena, MITS 43


js4.html

<html>
<body>

<h2>External JavaScript</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p>(myFunction is stored in an external file called "myScript.js")</p>

<script src="myScript.js"></script>

</body>
</html>

Parul Saxena, MITS 44


External JavaScript Advantages
• Placing scripts in external files has some
advantages:
– It separates HTML and code
– It makes HTML and JavaScript easier to read and
maintain
– Cached JavaScript files can speed up page loads
• To add several script files to one page - use
several script tags:
• Example
• <script src="myScript1.js"></script>
<script src="myScript2.js"></script>

Parul Saxena, MITS 45


JavaScript Print
• The only exception is that you can call the window.print() method in
the browser to print the content of the current window.

<html>
<body>

<h2>The window.print() Method</h2>

<p>Click the button to print the current page.</p>

<button onclick="window.print()">Print this page</button>

</body>
</html>

Parul Saxena, MITS 46


Function Return
• When JavaScript reaches a return statement, the function will stop executing.
• If the function was invoked from a statement, JavaScript will "return" to execute
the code after the invoking statement.
• Functions often compute a return value. The return value is "returned" back to the
"caller":
• Example
• Calculate the product of two numbers, and return the result:
• var x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}

• The result in x will be:


12

Parul Saxena, MITS 47


JavaScript Functions
• A JavaScript function is a block of code designed to perform a particular task.
• A JavaScript function is executed when "something" invokes it (calls it).

<html>
<body>

<h2>JavaScript Functions</h2>

<p>This example calls a function which performs a calculation, and returns the result:</p>

<p id="demo"></p>

<script>
function myFunction(p1, p2) {
return p1 * p2;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>

</body>
</html>

Parul Saxena, MITS 48


JavaScript Objects
• Real Life Objects, Properties, and Methods
• In real life, a car is an object.
• A car has properties like weight and color,
and methods like start and stop:
Object Properties Methods

car.name = Fiat car.start()

car.model = 500 car.drive()

car.weight = 850kg car.brake()

car.color = white car.stop()

Parul Saxena, MITS 49


• All cars have the same properties, but the
property values differ from car to car.
• All cars have the same methods, but the
methods are performed at different times.

Parul Saxena, MITS 50


JavaScript Objects
• This code assigns a simple value (Fiat) to a variable named
car:
var car = "Fiat";
• Objects are variables too. But objects can contain many
values.
• This code assigns many values (Fiat, 500, white) to
a variable named car:
var car = {type:"Fiat", model:"500", color:"white"};
• The values are written as name:value pairs (name and value
separated by a colon).
• JavaScript objects are containers for named values called
properties or methods.

Parul Saxena, MITS 51


<html>
<body>

<h2>JavaScript Objects</h2>

<p id="demo"></p>

<script>
// Create an object:
var car = {type:"Fiat", model:"500", color:"white"};

// Display some data from the object:


document.getElementById("demo").innerHTML = "The car type is " + car.type;
</script>

</body>
</html>

Parul Saxena, MITS 52


JavaScript Objects

• JavaScript objects are written with curly braces {}.


• Object properties are written as name:value
pairs, separated by commas.
• Example
• var person = {firstName:"John",
lastName:“Roy", age:50, eyeColor:"blue"};
• The object (person) in the example above has 4
properties: firstName, lastName, age, and
eyeColor.

Parul Saxena, MITS 53


<html>
<body>

<h2>JavaScript Objects</h2>

<p id="demo"></p>

<script>
// Create an object:
var person = {firstName:"John", lastName:"Roy", age:50, eyeColor:"blue"};

// Display some data from the object:


document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>

Parul Saxena, MITS 54


• Object Properties
– The name:values pairs in JavaScript objects are called properties:
– Property Property Value
firstName John
lastName Roy
age 50
eyeColor blue
• Accessing Object Properties
You can access object properties in two ways:
objectName.propertyName
or
objectName["propertyName"]
• Example1
person.lastName; OR person["lastName"];

Parul Saxena, MITS 55


<html>
<body>

<h2>JavaScript Objects</h2>

<p>There are two different ways to access an object property.</p>

<p>You can use person.property or person["property"].</p>

<p id="demo"></p>

<script>
// Create an object:
var person = {
firstName: "John",
lastName : “Roy",
id : 5566
};
// Display some data from the object:
document.getElementById("demo").innerHTML = person["firstName"] + " " + person["lastName"];
</script>

</body>
</html>

Parul Saxena, MITS 56


HTML Events
• An HTML event can be something the browser
does, or something a user does.
• Here are some examples of HTML events:
– An HTML web page has finished loading
– An HTML input field was changed
– An HTML button was clicked

Parul Saxena, MITS 57


• HTML allows event handler attributes, with JavaScript
code, to be added to HTML elements.
• With single quotes:
– <element event='some JavaScript'>
• With double quotes:
– <element event="some JavaScript">
• In the following example, an onclick attribute (with
code), is added to a <button> element:
• Example
– <button onclick="document.getElementById('demo').inner
HTML = Date()">The time is?</button>

Parul Saxena, MITS 58


<html>
<body>

<button
onclick="document.getElementById('demo').innerHTML=Date()">T
he time is?</button>

<p id="demo"></p>

</body>
</html>

Parul Saxena, MITS 59


JavaScript Strings

• JavaScript strings are used for storing and


manipulating text.
• A JavaScript string is zero or more characters
written inside quotes.
• var carName1 = "Volvo XC60"; // Double quotes
var carName2 = 'Volvo XC60'; // Single quotes
• var answer1 = "It's alright";
var answer2 = "He is called 'Johnny'";
var answer3 = 'He is called "Johnny"';
Parul Saxena, MITS 60
<html>
<body>

<h2>JavaScript Strings</h2>

<p>You can use quotes inside a string, as long as they don't match the quotes
surrounding the string.</p>

<p id="demo"></p>

<script>
var answer1 = "It's alright";
var answer2 = "He is called 'Johnny'";
var answer3 = 'He is called "Johnny"';

document.getElementById("demo").innerHTML =
answer1 + "<br>" + answer2 + "<br>" + answer3;
</script>

</body>
</html>

Parul Saxena, MITS 61


String Length
• To find the length of a string, use the built-
in length property:
• Example
• var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;

Parul Saxena, MITS 62


<html>
<body>

<h2>JavaScript String Properties</h2>

<p>The length property returns the length of a string:</p>

<p id="demo"></p>

<script>
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.getElementById("demo").innerHTML = txt.length;
</script>

</body>
</html>

Parul Saxena, MITS 63


Escape Character
• Because strings must be written within quotes, JavaScript
will misunderstand this string:
• var x = "We are the “BEST”.";
• The solution to avoid this problem, is to use the backslash
escape character.
• The backslash (\) escape character turns special characters
into string characters:
• Code Result Description
\‘ ‘ Single quote
\“ “ Double quote
\\ \ Backslash
• The sequence \" inserts a double quote in a string:
• Example
var x = "We are the \”BEST\”.";

Parul Saxena, MITS 64


<html>
<body>

<h2>JavaScript Strings</h2>

<p>The escape sequence \" inserts a double quote in a string.</p>

<p id="demo"></p>

<script>
var x = "We are the \"BEST\".";
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Parul Saxena, MITS 65


• The sequence \' inserts a single quote in a string:
• Example
var x = 'It\'s alright.';
<html>
<body>

<h2>JavaScript Strings</h2>

<p>The escape sequence \' inserts a single quote in a string.</p>

<p id="demo"></p>

<script>
var x = 'It\'s alright.';
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Parul Saxena, MITS 66


• The sequence \\ inserts a backslash in a string:
• Example
var x = "The character \\ is called backslash.";
<html>
<body>

<h2>JavaScript Strings</h2>

<p>The escape sequence \\ inserts a backslash in a string.</p>

<p id="demo"></p>

<script>
var x = "The character \\ is called backslash.";
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Parul Saxena, MITS 67


Breaking Long Code Lines
• For best readability, programmers often like to avoid code lines longer
than 80 characters.
• If a JavaScript statement does not fit on one line, the best place to
break it is after an operator:
• Example
document.getElementById("demo").innerHTML =
"Hello Dolly!";
• You can also break up a code line within a text string with a single
backslash:
• Example
document.getElementById("demo").innerHTML = "Hello \
Dolly!";
NOTE: The \ method is not the preferred method. It might not have
universal support. Some browsers do not allow spaces behind
the \ character.

Parul Saxena, MITS 68


<html>
<body>

<h2>JavaScript Strings</h2>

<p>
You can break a code line within a text string with a backslash.
</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello \
Dolly!";
</script>

</body>
</html>

Parul Saxena, MITS 69


• A safer way to break up a string, is to use
string addition:
• Example
document.getElementById("demo").innerHT
ML = "Hello " +
"Dolly!";

Parul Saxena, MITS 70


Finding a String in a String
• The indexOf() method returns the index of (the
position of) the first occurrence of a specified text in
a string:
• Example
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");
• JavaScript counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is
the third ...

Parul Saxena, MITS 71


<html>
<body>

<h2>JavaScript String Methods</h2>

<p>The indexOf() method returns the position of the first occurrence of a


specified text:</p>

<p id="demo"></p>

<script>
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");
document.getElementById("demo").innerHTML = pos;
</script>

</body>
</html>

Parul Saxena, MITS 72


• The lastIndexOf() method returns the index of
the last occurrence of a specified text in a string:
• Example
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate");
• Both indexOf(), and lastIndexOf() return -1 if the text is not
found.
• Example
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("John");

Parul Saxena, MITS 73


<html>
<body>

<h2>JavaScript String Methods</h2>

<p>The lastIndexOf() method returns the position of the last occurrence of a


specified text:</p>

<p id="demo"></p>

<script>
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate");
document.getElementById("demo").innerHTML = pos;
</script>

</body>
</html>

Parul Saxena, MITS 74


• Both methods accept a second parameter as the starting
position for the search:
• Example
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate", 15);

Parul Saxena, MITS 75


<html>
<body>

<h2>JavaScript String Methods</h2>

<p>The indexOf() method accepts a second parameter as the starting position


for the search:</p>

<p id="demo"></p>

<script>
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate",15);
document.getElementById("demo").innerHTML = pos;
</script>

</body>
</html>

Parul Saxena, MITS 76


• The lastIndexOf() methods searches backwards (from the end
to the beginning), meaning: if the second parameter is 15, the
search starts at position 15, and searches to the beginning of
the string.
• Example
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate", 15);

Parul Saxena, MITS 77


<html>
<body>

<h2>JavaScript String Methods</h2>

<p>The lastIndexOf() method accepts a second parameter as the starting position for the search.</p>
<p>Remember that the lastIndexOf() method searches backwards, so position 15 means start the
search at position 15, and search to the beginning.</p>
<p>Position 15 is position 15 from the beginning.</p>

<p id="demo"></p>

<script>
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate", 15);
document.getElementById("demo").innerHTML = pos;
</script>

</body>
</html>

Parul Saxena, MITS 78


Searching for a String in a String
• The search() method searches a string for a specified
value and returns the position of the match:
• Example
• var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");
• The two methods, indexOf() and search(), are equal?
• They accept the same arguments (parameters), and
return the same value?
• The two methods are NOT equal.
– The search() method cannot take a second start position
argument.

Parul Saxena, MITS 79


Extracting String Parts
• There are 3 methods for extracting a part of a string:
• slice(start, end)
• substring(start, end)
• substr(start, length)
• The slice() Method
• slice() extracts a part of a string and returns the extracted part in a
new string.
• The method takes 2 parameters: the start position, and the end
position (end not included).
• This example slices out a portion of a string from position 7 to
position 12 (13-1):
• Example
• var str = "Apple, Banana, Kiwi";
var res = str.slice(7, 13);
• The result of res will be:
Banana
Remember: JavaScript counts positions from zero. First position is 0.

Parul Saxena, MITS 80


<html>
<body>

<h2>JavaScript String Methods</h2>

<p>The slice() method extract a part of a string


and returns the extracted parts in a new string:</p>

<p id="demo"></p>

<script>
var str = "Apple, Banana, Kiwi";
var res = str.slice(7,13);
document.getElementById("demo").innerHTML = res;
</script>

</body>
</html>

Parul Saxena, MITS 81


• If a parameter is negative, the position is
counted from the end of the string.
• This example slices out a portion of a string
from position -12 to position -6:
• Example
• var str = "Apple, Banana, Kiwi";
var res = str.slice(-12, -6);
• The result of res will be:
• Banana

Parul Saxena, MITS 82


<html>
<body>

<h2>JavaScript String Methods</h2>

<p>The slice() method extract a part of a string


and returns the extracted parts in a new string:</p>

<p id="demo"></p>

<script>
var str = "Apple, Banana, Kiwi";
var res = str.slice(-12,-6);
document.getElementById("demo").innerHTML = res;
</script>

</body>
</html>

Parul Saxena, MITS 83


• If you omit the second parameter, the method will slice out the rest of the
string:
<html>
<body>

<h2>JavaScript String Methods</h2>

<p>The slice() method extract a part of a string


and returns the extracted parts in a new string:</p>

<p id="demo"></p>

<script>
var str = "Apple, Banana, Kiwi";
var res = str.slice(7);
document.getElementById("demo").innerHTML = res;
</script>

</body>
</html>

Parul Saxena, MITS 84


counting from the end:
<html>
<body>

<h2>JavaScript String Methods</h2>

<p>The slice() method extract a part of a string


and returns the extracted parts in a new string:</p>

<p id="demo"></p>

<script>
var str = "Apple, Banana, Kiwi";
var res = str.slice(-12)
document.getElementById("demo").innerHTML = res;
</script>

</body>
</html>

Parul Saxena, MITS 85


The substring() Method
• substring() is similar to slice().
• The difference is that substring() cannot
accept negative indexes.
• Example
• var str = "Apple, Banana, Kiwi";
var res = str.substring(7, 13);
• The result of res will be:
• Banana

Parul Saxena, MITS 86


The substr() Method
• substr() is similar to slice().
• The difference is that the second parameter specifies
the length of the extracted part.
• Example
• var str = "Apple, Banana, Kiwi";
var res = str.substr(7, 6);
• The result of res will be:
Banana
• If we omit the second parameter, substr() will slice out the
rest of the string.
• Example
var str = "Apple, Banana, Kiwi";
var res = str.substr(7);
• The result of res will be:
Banana, Kiwi
Parul Saxena, MITS 87
• If the first parameter is negative, the position
counts from the end of the string.
• Example
• var str = "Apple, Banana, Kiwi";
var res = str.substr(-4);
• The result of res will be:
• Kiwi

Parul Saxena, MITS 88


<html>
<body>

<h2>JavaScript String Methods</h2>

<p>The substr() method extract a part of a string


and returns the extracted parts in a new string:</p>

<p id="demo"></p>

<script>
var str = "Apple, Banana, Kiwi";
var res = str.substr(-4);
document.getElementById("demo").innerHTML = res;
</script>

</body>
</html>

Parul Saxena, MITS 89


Replacing String Content
• The replace() method replaces a specified
value with another value in a string:
• Example
• str = "Please visit Microsoft!";
var n = str.replace("Microsoft", “Yahoo");

Parul Saxena, MITS 90


<html>

<body>

<h2>JavaScript String Methods</h2>

<p> Replace "Microsoft" with "Yahoo" in the paragraph below: </p>

<button onclick="myFunction()">Try it</button>

<p id="demo"> Please visit Microsoft! </p>

<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var txt = str.replace("Microsoft","Yahoo");
document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

Parul Saxena, MITS 91


• By default, the replace() method replaces only the first match:
<html>
<body>

<h2>JavaScript String Methods</h2>

<p> Replace "Microsoft" with “Yahoo" in the paragraph below: </p>

<button onclick="myFunction()">Try it</button>

<p id="demo"> Please visit Microsoft and Microsoft! </p>

<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var txt = str.replace("Microsoft","Yahoo");
document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>
Parul Saxena, MITS 92
• By default, the replace() method is case
sensitive. Writing MICROSOFT (with upper-
case) will not work:
• Example
• str = "Please visit Microsoft!";
var n = str.replace("MICROSOFT", “Yahoo!");

Parul Saxena, MITS 93


<html>
<body>

<h2>JavaScript String Methods</h2>

<p>Try to replace "Microsoft" with "Yahoo!" in the paragraph below:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"> Please visit Microsoft! </p>

<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var txt = str.replace("MICROSOFT","Yahoo!");
document.getElementById("demo").innerHTML = txt;
}
</script>

<p><strong>Note:</strong> Nothing will happen. By default, the replace() method is case sensitive.
Writing MICROSOFT (with upper-case) will not work.</p>

</body>
</html>

Parul Saxena, MITS 94


• To replace case insensitive, use a regular
expression with an /i flag (insensitive):
• Example
• str = "Please visit Microsoft!";
var n = str.replace(/MICROSOFT/i, “Yahoo");

Parul Saxena, MITS 95


<html>
<body>

<h2>JavaScript String Methods</h2>

<p>Replace "Microsoft" with "Yahoo!" in the paragraph below:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Please visit Microsoft!</p>

<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var txt = str.replace(/MICROSOFT/i,"Yahoo!");
document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

Parul Saxena, MITS 96


• To replace all matches, use a regular expression with
a /g flag (global match):
• Example
• str = "Please visit Microsoft and Microsoft!";
var n = str.replace(/Microsoft/g, “Yahoo");

Parul Saxena, MITS 97


<html>
<body>

<h2>JavaScript String Methods</h2>

<p>Replace all occurrences of "Microsoft" with "Yahoo" in the paragraph below:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Please visit Microsoft and Microsoft!</p>

<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var txt = str.replace(/Microsoft/g,"Yahoo");
document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

Parul Saxena, MITS 98


Converting to Upper and Lower Case
• A string is converted to upper case
with toUpperCase():
• Example
• var text1 = "Hello World!"; // String
var text2 = text1.toUpperCase(); // text2 is text1
converted to upper
• A string is converted to lower case
with toLowerCase():
• Example
• var text1 = "Hello World!"; // String
var text2 = text1.toLowerCase(); // text2 is text1
converted to lower
Parul Saxena, MITS 99
<html>
<body>

<p>Convert string to upper case:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Hello World!</p>

<script>
function myFunction() {
var text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML = text.toUpperCase();
}
</script>

</body>
</html>

Parul Saxena, MITS 100


The concat() Method
• concat() joins two or more strings:
• Example
• var text1 = "Hello";
var text2 = "World";
var text3 = text1.concat(" ", text2);
• The concat() method can be used instead of the
plus operator. These two lines do the same:
• Example
• var text = "Hello" + " " + "World!";
var text = "Hello".concat(" ", "World!");

Parul Saxena, MITS 101


<html>
<body>

<h2>JavaScript String Methods</h2>

<p>The concat() method joins two or more strings:</p>

<p id="demo"></p>

<script>
var text1 = "Hello";
var text2 = "World!";
var text3 = text1.concat(" ",text2);
document.getElementById("demo").innerHTML = text3;
</script>

</body>
</html>

Parul Saxena, MITS 102


String.trim()

• The trim() method removes whitespace from


both sides of a string:
• Example
• var str = " Hello World! ";
alert(str.trim());

Parul Saxena, MITS 103


<html>
<body>

<h2>JavaScript String.trim()</h2>

<p>Click the button to alert the string with removed whitespace.</p>

<button onclick="myFunction()">Try it</button>

<p><strong>Note:</strong> The trim() method is not supported in Internet Explorer 8 and earlier
versions.</p>

<script>
function myFunction() {
var str = " Hello World! ";
alert(str);
}
</script>

</body>
</html>

Parul Saxena, MITS 104


Extracting String Characters
• The charAt() Method
• The charAt() method returns the character at
a specified index (position) in a string:
• Example
• var str = "HELLO WORLD";
str.charAt(0); // returns H

Parul Saxena, MITS 105


<html>
<body>

<h2>JavaScript String Methods</h2>

<p>The charAt() method returns the character at a given position in a


string:</p>

<p id="demo"></p>

<script>
var str = "HELLO WORLD";
document.getElementById("demo").innerHTML = str.charAt(0);
</script>

</body>
</html>

Parul Saxena, MITS 106


Converting a String to an Array

• A string can be converted to an array with


the split() method:
• Example
• var txt = "a,b,c,d,e"; // String
txt.split(","); // Split on commas
txt.split(" "); // Split on spaces
txt.split("|"); // Split on pipe

Parul Saxena, MITS 107


<html>
<body>

<p>Click "Try it" to display the first array element, after a string split.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var str = "a,b,c,d,e,f";
var arr = str.split(",");
document.getElementById("demo").innerHTML = arr[0];
}
</script>

</body>
</html>

Parul Saxena, MITS 108


Adding Numbers and Strings

• var x = 10;
var y = 20;
var z = x + y; // z will be 30 (a number)
• var x = "10";
var y = "20";
var z = x + y; // z will be 1020 (a string)
• var x = 10;
var y = "20";
var z = x + y; // z will be 1020 (a string)
• var x = "10";
var y = 20;
var z = x + y; // z will be 1020 (a string)
• var x = 10;
var y = 20;
var z = "The result is: " + x + y; //?????
• The result is: 1020

Parul Saxena, MITS 109


• var x = 10;
var y = 20;
var z = "30";
var result = x + y + z;
• 3030

Parul Saxena, MITS 110


Numeric Strings

• JavaScript strings can have numeric content:


• var x = 100; // x is a number
var y = "100"; // y is a string
• JavaScript will try to convert strings to numbers in all numeric operations:
• This will work:
• var x = "100";
var y = "10";
var z = x / y;
• // z will be 10

• var x = "100";
var y = "10";
var z = x * y;
• // z will be 1000

Parul Saxena, MITS 111


• var x = "100";
var y = "10";
var z = x - y;
• // z will be 90

Parul Saxena, MITS 112


NaN - Not a Number (type.html)
• NaN is a JavaScript reserved word indicating that a number is not a legal number.
• Trying to do arithmetic with a non-numeric string will result in NaN (Not a
Number):
• Example
• var x = 100 / "Apple"; // x will be NaN (Not a Number)
• However, if the string contains a numeric value , the result will be a number:
• var x = 100 / "10"; // x will be 10
• You can use the global JavaScript function isNaN() to find out if a value is a
number:
• var x = 100 / "Apple";
isNaN(x); // returns true because x is Not a Number
• If you use NaN in a mathematical operation, the result will also be NaN:
• var x = NaN;
var y = 5;
var z = x + y; // z will be NaN
• the result might be a concatenation:
• var x = NaN;
var y = "5";
var z = x + y; // z will be NaN5
• NaN is a number: typeof NaN returns number:
• typeof NaN; // returns "number"

Parul Saxena, MITS 113


The toFixed() Method

• toFixed() returns a string, with the number


written with a specified number of decimals:
• Example
• var x = 9.656;
x.toFixed(0); // returns 10
x.toFixed(2); // returns 9.66
x.toFixed(4); // returns 9.6560
x.toFixed(6); // returns 9.656000

Parul Saxena, MITS 114


The toPrecision() Method

• toPrecision() returns a string, with a number


written with a specified length:
• Example
• var x = 9.656;
x.toPrecision(); // returns 9.656
x.toPrecision(2); // returns 9.7
x.toPrecision(4); // returns 9.656
x.toPrecision(6); // returns 9.65600

Parul Saxena, MITS 115


The Number() Method
• Number() can be used to convert JavaScript variables to
numbers:
• Example
• Number(true); // returns 1
Number(false); // returns 0
Number("10"); // returns 10
Number(" 10"); // returns 10
Number("10 "); // returns 10
Number(" 10 "); // returns 10
Number("10.33"); // returns 10.33
Number("10,33"); // returns NaN
Number("10 33"); // returns NaN
Number("John"); // returns NaN

Parul Saxena, MITS 116


<html>
<body>

<h2>JavaScript Global Methods</h2>

<p>The Number() method converts variables to numbers:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
Number(true) + "<br>" +
Number(false) + "<br>" +
Number("10") + "<br>" +
Number(" 10") + "<br>" +
Number("10 ") + "<br>" +
Number(" 10 ") + "<br>" +
Number("10.33") + "<br>" +
Number("10,33") + "<br>" +
Number("10 33") + "<br>" +
Number("John");
</script>

</body>
</html>

Parul Saxena, MITS 117


The parseFloat() Method
• parseFloat() parses a string and returns a number.
Spaces are allowed. Only the first number is
returned:
• Example
• parseFloat("10"); // returns 10
parseFloat("10.33"); // returns 10.33
parseFloat("10 20 30"); // returns 10
parseFloat("10 years"); // returns 10
parseFloat("years 10"); // returns NaN
• If the number cannot be converted, NaN (Not a
Number) is returned.
Parul Saxena, MITS 118
JavaScript Arrays
• JavaScript arrays are used to store multiple values in a
single variable.
• An array is a special variable, which can hold more than one
value at a time.
• If you have a list of items (a list of car names, for example),
storing the cars in single variables could look like this:
• var car1 = "Saab";
var car2 = "Volvo";
var car3 = "BMW";
• However, what if you want to loop through the cars and
find a specific one? And what if you had not 3 cars, but
300?
• The solution is an array!
• An array can hold many values under a single name, and
you can access the values by referring to an index number.

Parul Saxena, MITS 119


• Creating an Array
• Using an array literal is the easiest way to
create a JavaScript Array.
• Syntax:
• var array_name = [item1, item2, ...];

• Example
• var cars = ["Saab", "Volvo", "BMW"];

Parul Saxena, MITS 120


• Example
var cars = ["Saab", "Volvo", "BMW"];
<html>
<body>

<h2>JavaScript Arrays</h2>

<p id="demo"></p>

<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>

</body>
</html>

Parul Saxena, MITS 121


• JavaScript arrays are written with square
brackets.
• Array items are separated by commas.
• The following code declares (creates) an array
called cars, containing three items (car
names):
• Example
• var cars = ["Saab", "Volvo", "BMW"];

Parul Saxena, MITS 122


Access the Elements of an Array
• we access an array element by referring to
the index number.
• This statement accesses the value of the first
element in cars:
• var name = cars[0];
• Example
• var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHT
ML = cars[0];

Parul Saxena, MITS 123


<html>
<body>

<h2>JavaScript Arrays</h2>

<p>Array indexes are zero-based, which means the first item is [0].</p>

<p id="demo"></p>

<script>
var cars = ["Saab","Volvo","BMW"];

document.getElementById("demo").innerHTML = cars[0];
</script>

</body>
</html>

Parul Saxena, MITS 124


What is the output…
var cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
document.getElementById("demo").innerHTML = cars[0];

Parul Saxena, MITS 125


Arrays are Objects
• Arrays are a special type of objects.
• Arrays use numbers to access its "elements". In this
example, person[0] returns John:
• Array:
• var person = ["John", "Doe", 46];
• Objects use names to access its "members". In this
example, person.firstName returns John:
• Object:
• var person = {firstName:"John", lastName:"Doe", age:46};

Parul Saxena, MITS 126


<html>
<body>

<h2>JavaScript Objects</h2>
<p>JavaScript uses names to access object properties.</p>
<p id="demo"></p>

<script>
var person = {firstName:"John", lastName:"Doe", age:46};
document.getElementById("demo").innerHTML =
person["firstName"];
</script>

</body>
</html>
Parul Saxena, MITS 127
Array Properties and Methods
• The real strength of JavaScript arrays are the built-in
array properties and methods:
• Examples
• var x = cars.length; // The length property returns the
number of elements
var y = cars.sort(); // The sort() method sorts arrays
• The length Property
• The length property of an array returns the length of an
array (the number of array elements).
• Example
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // the length of fruits is 4

Parul Saxena, MITS 128


<html>
<body>

<h2>JavaScript Arrays</h2>
<p>The length property returns the length of an array.</p>

<p id="demo"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.length;
</script>

</body>
</html>

Parul Saxena, MITS 129


• Accessing the Last Array Element
• Example
• fruits = ["Banana", "Orange", "Apple", "Mango"];
var last = fruits[fruits.length - 1];

Parul Saxena, MITS 130


• Looping Array Elements
• The safest way to loop through an array, is using
a for loop:
• Example
• var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;

text = "<ul>";
for (i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
Parul Saxena, MITS 131
<html>
<body>

<h2>JavaScript Arrays</h2>

<p>The best way to loop through an array is using a standard for loop:</p>

<p id="demo"></p>

<script>
var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;

text = "<ul>";
for (i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Parul Saxena, MITS 132


Array.forEach() function:
var fruits, text;
fruits =
["Banana", "Orange", "Apple", "Mango"];

text = "<ul>";
fruits.forEach(myFunction);
text += "</ul>";

function myFunction(value) {
text += "<li>" + value + "</li>";
}

Parul Saxena, MITS 133


<html>
<body>

<h2>JavaScript Arrays</h2>

<p>Array.forEach() calls a function for each array element.</p>

<p>Array.forEach() is not supported in Internet Explorer 8 or earlier.</p>

<p id="demo"></p>

<script>
var fruits, text;
fruits = ["Banana", "Orange", "Apple", "Mango"];

text = "<ul>";
fruits.forEach(myFunction);
text += "</ul>";
document.getElementById("demo").innerHTML = text;

function myFunction(value) {
text += "<li>" + value + "</li>";
}
</script>

</body>
</html>

Parul Saxena, MITS 134


Adding Array Elements
• The easiest way to add a new element to an
array is using the push() method:
• Example
• var fruits =
["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); // adds a new element
(Lemon) to fruits

Parul Saxena, MITS 135


<html>
<body>

<h2>JavaScript Arrays</h2>

<p>The push method appends a new element to an array.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
fruits.push("Lemon");
document.getElementById("demo").innerHTML = fruits;
}
</script>

</body>
</html>

Parul Saxena, MITS 136


• The length property provides an easy way to append
new elements to an array without using the push()
method.
var fruits =
["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon"; // adds a new
element (Lemon) to fruits

Parul Saxena, MITS 137


<html>
<body>

<h2>JavaScript Arrays</h2>

<p>The length property provides an easy way to append new elements to an array without using the
push() method.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
fruits[fruits.length] = "Lemon";
document.getElementById("demo").innerHTML = fruits;
}
</script>

</body>
</html>

Parul Saxena, MITS 138


OUTPUT…..
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[6] = "Lemon";

//adds a new element (Lemon) to fruits

Parul Saxena, MITS 139


<html>
<body>

<h2>JavaScript Arrays</h2>

<p>Adding elements with high indexes can create undefined "holes" in an array.</p>

<p id="demo"></p>

<script>
var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[6] = "Lemon";

fLen = fruits.length;
text = "";
for (i = 0; i < fLen; i++) {
text += fruits[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Parul Saxena, MITS 140


Popping and Pushing
• When we work with arrays, it is easy to remove elements
and add new elements.
• This is what popping and pushing is:
• Popping items out of an array, or pushing items into an
array.
• Popping
The pop() method removes the last element from an array:
• Example
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop(); // Removes the last element ("Mango")
from fruits

Parul Saxena, MITS 141


<html>
<body>

<h2>JavaScript Array Methods</h2>

<h2>pop()</h2>

<p>The pop() method removes the last element from an array.</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits.pop();
document.getElementById("demo2").innerHTML = fruits;
</script>

</body>
</html>

Parul Saxena, MITS 142


• The pop() method returns the value that was "popped out":
• Example
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.pop(); // the value of x is "Mango"

Parul Saxena, MITS 143


<html>
<body>

<h2>JavaScript Array Methods</h2>

<h2>pop()</h2>

<p>The pop() method removes the last element from an array.</p>

<p>The return value of the pop() method is the removed item.</p>

<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
document.getElementById("demo2").innerHTML = fruits.pop();
document.getElementById("demo3").innerHTML = fruits;
</script>

</body>
</html>

Parul Saxena, MITS 144


• Pushing
• The push() method adds a new element to an array
(at the end):
• Example
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi"); // Adds a new element
("Kiwi") to fruits

Parul Saxena, MITS 145


<html>
<body>

<h2>JavaScript Array Methods</h2>

<h2>push()</h2>

<p>The push() method appends a new element to an array.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
fruits.push("Kiwi");
document.getElementById("demo").innerHTML = fruits;
}
</script>

</body>
</html>

Parul Saxena, MITS 146


• The push() method returns the new array length:
• Example
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.push("Kiwi"); // the value of x is 5

Parul Saxena, MITS 147


<html>
<body>

<h2>JavaScript Array Methods</h2>

<h2>push()</h2>

<p>The push() method returns the new array length.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;

function myFunction() {
document.getElementById("demo2").innerHTML = fruits.push("Kiwi");
document.getElementById("demo1").innerHTML = fruits;
}
</script>

</body>
</html>

Parul Saxena, MITS 148


• Shifting Elements
Shifting is equivalent to popping, working on the
first element instead of the last.
The shift() method removes the first array element
and "shifts" all other elements to a lower index.
• Example
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift(); // Removes the first element "Banana" from fruits
• The shift() method returns the string that was "shifted out":
• Example
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.shift(); // the value of x is "Banana"

Parul Saxena, MITS 149


<html>
<body>

<h2>JavaScript Array Methods</h2>

<h2>shift()</h2>

<p>The shift() method returns the element that was shifted out.</p>

<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
document.getElementById("demo2").innerHTML = fruits.shift();
document.getElementById("demo3").innerHTML = fruits;
</script>

</body>
</html>

Parul Saxena, MITS 150


• The unshift() method adds a new element to an array
(at the beginning), and "unshifts" older elements:
• Example
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon"); // Adds a new element
"Lemon" to fruits
• The unshift() method returns the new array length.
• Example
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon"); // Returns 5

Parul Saxena, MITS 151


<html>
<body>

<h2>JavaScript Array Methods</h2>

<h2>unshift()</h2>

<p>The unshift() method adds new elements to the beginning of an array.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
fruits.unshift("Lemon");
document.getElementById("demo").innerHTML = fruits;
}
</script>

</body>
</html>

Parul Saxena, MITS 152


<html>
<body>

<h2>JavaScript Array Methods</h2>

<h2>unshift()</h2>

<p>The unshift() method returns the length of the new array:</p>

<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
document.getElementById("demo2").innerHTML = fruits.unshift("Lemon");
document.getElementById("demo3").innerHTML = fruits;
</script>

</body>
</html>

Parul Saxena, MITS 153


Changing Elements
• Array elements are accessed using their index
number:
• Array indexes start with 0. [0] is the first array
element, [1] is the second, [2] is the third ...
• Example
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[0] = "Kiwi"; // Changes the first element of fruits to
"Kiwi"

Parul Saxena, MITS 154


<html>
<body>
<h2>JavaScript Array Methods</h2>
<p id="demo1"></p>
<script>
var fruits = ["Banana", "Orange", "Apple",
"Mango"];
fruits[0] = "Kiwi";
document.getElementById("demo1").innerHTML =
fruits;
</script>
</body>
</html>
Parul Saxena, MITS 155
• The length property provides an easy way to
append a new element to an array:
• Example
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Kiwi"; // Appends "Kiwi" to fruits
<html>
<body>
<h2>JavaScript Array Methods</h2>
<p id="demo1"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Kiwi";
document.getElementById("demo1").innerHTML = fruits;
</script>
</body>
</html>

Parul Saxena, MITS 156


• Deleting Elements
• Since JavaScript arrays are objects, elements can be deleted by
using the JavaScript operator delete:
• Example
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0]; // Changes the first element in fruits
to undefined
• In JavaScript, a variable without a value, has the value undefined.
The type is also undefined.
NOTE: Using delete may leave undefined holes in the array. Use pop()
or shift() instead.
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0];
document.getElementById("demo1").innerHTML = typeof fruits[0];
</script>

Parul Saxena, MITS 157


<html>
<body>

<h2>JavaScript Array Methods</h2>

<p>Deleting elements leaves undefined holes in an array.</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML =
"The first fruit is: " + fruits[0];
delete fruits[0];
document.getElementById("demo2").innerHTML =
"The first fruit is: " + fruits[0];
</script>

</body>
</html>

Parul Saxena, MITS 158


Splicing an Array
• The splice() method can be used to add new
items to an array:
• Example
• var fruits =
["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
• The first parameter (2) defines the
position where new elements should
be added (spliced in).
• The second parameter (0) defines how
many elements should be removed.
• The rest of the parameters ("Lemon" , "Kiwi")
define the new elements to be added.

Parul Saxena, MITS 159


<html>
<body>

<h2>JavaScript Array Methods</h2>

<h2>splice()</h2>

<p>The splice() method adds new elements to an array.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = "Original Array:<br>" + fruits;
function myFunction() {
fruits.splice(2, 0, "Lemon", "Kiwi");
document.getElementById("demo2").innerHTML = "New Array:<br>" + fruits;
}
</script>

</body>
</html>

Parul Saxena, MITS 160


• The splice() method returns an array with the
deleted items:
• Example
• var fruits =
["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 2, "Lemon", "Kiwi");

Parul Saxena, MITS 161


<html>
<body>

<h2>JavaScript Array Methods</h2>

<h2>splice()</h2>

<p>The splice() method adds new elements to an array, and returns an array with the deleted elements (if any).</p>

<button onclick="myFunction()">Try it</button>

<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = "Original Array:<br> " + fruits;

function myFunction() {
var removed = fruits.splice(2, 2, "Lemon", "Kiwi");
document.getElementById("demo2").innerHTML = "New Array:<br>" + fruits;
document.getElementById("demo3").innerHTML = "Removed Items:<br> " + removed;
}
</script>

</body>
</html>

Parul Saxena, MITS 162


• Using splice() to Remove Elements
• With clever parameter setting, we can use splice() to remove
elements without leaving "holes" in the array:
• Example
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1); // Removes the first element of fruits
• The first parameter (0) defines the position where new
elements should be added (spliced in).
• The second parameter (1) defines how many elements should
be removed.

Parul Saxena, MITS 163


<html>
<body>

<h2>JavaScript Array Methods</h2>

<h2>splice()</h2>

<p>The splice() methods can be used to remove array elements.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
function myFunction() {
fruits.splice(0, 1);
document.getElementById("demo").innerHTML = fruits;
}
</script>

</body>
</html>

Parul Saxena, MITS 164


Merging (Concatenating) Arrays
• The concat() method creates a new array by
merging (concatenating) existing arrays.
• The concat() method does not change the
existing arrays. It always returns a new array.
• The concat() method can take any number of
array arguments.
• The concat() method can also take strings as
arguments.

Parul Saxena, MITS 165


<html>
<body>

<h2>JavaScript Array Methods</h2>

<h2>concat()</h2>

<p>The concat() method is used to merge (concatenate) arrays:</p>

<p id="demo"></p>

<script>
var fruit = ["Apple", "Mango"];
var vegetable = ["Tomato", "Potato", "Onion"];
var inAll = fruit.concat(vegetable);

document.getElementById("demo").innerHTML = inAll;
</script>

</body>
</html>

Parul Saxena, MITS 166


Example (Merging Three Arrays)

<html>
<body>

<h2>JavaScript Array Methods</h2>

<h2>concat()</h2>

<p>The concat() method is used to merge (concatenate) arrays:</p>

<p id="demo"></p>

<script>
var arr1 = ["Apple", "Mango"];
var arr2 = ["Tomato", "Potato", "Onion"];
var arr3 = ["Jeera", "Meetha Neem"];

var inAll = arr1.concat(arr2, arr3);

document.getElementById("demo").innerHTML = inAll;
</script>

</body>
</html>

Parul Saxena, MITS 167


Example (Merging an Array with Values)
<html>
<body>

<h2>JavaScript Array Methods</h2>

<h2>concat()</h2>

<p>The concat() method can also merge string values to arrays:</p>

<p id="demo"></p>

<script>
var arr1 = ["Apple", "Mango", "Banana"];
var inAll = arr1.concat("Grapes");
document.getElementById("demo").innerHTML = inAll;
</script>

</body>
</html>

Parul Saxena, MITS 168


• Slicing an Array
The slice() method slices out a piece of an array
into a new array.
• This example slices out a part of an array starting
from array element 1 ("Orange"):
• Example
• var fruits =
["Banana", "Orange", "Lemon", "Apple", "Mango"
];
var citrus = fruits.slice(1);
• The slice() method creates a new array. It does
not remove any elements from the source array.

Parul Saxena, MITS 169


<html>
<body>

<h2>JavaScript Array Methods</h2>

<h2>slice()</h2>

<p>This example slices out a part of an array starting from array element
("Orange"):</p>

<p id="demo"></p>

<script>
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1);
document.getElementById("demo").innerHTML = fruits + "<br><br>" + citrus;
</script>

</body>
</html>

Parul Saxena, MITS 170


• This example slices out a part of an array
starting from array element 3 ("Apple"):
• Example
• var fruits =
["Banana", "Orange", "Lemon", "Apple", "Man
go"];
var citrus = fruits.slice(3);

Parul Saxena, MITS 171


• The slice() method can take two arguments
like slice(1, 3).
• The method then selects elements from the start
argument, and up to (but not including) the end
argument.
• Example
• var fruits =
["Banana", "Orange", "Lemon", "Apple", "Mango"
];
var citrus = fruits.slice(1, 3);
Parul Saxena, MITS 172
• Sorting an Array
• The sort() method sorts an array alphabetically:
• Example
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // Sorts the elements of fruits
• Reversing an Array
• The reverse() method reverses the elements in an array.
• You can use it to sort an array in descending order:
• Example
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // First sort the elements of fruits
fruits.reverse(); // Then reverse the order of the elements

Parul Saxena, MITS 173


<html>
<body>

<h2>JavaScript Array Sort Reverse</h2>

<p>The reverse() method reverses the elements in an array.</p>


<p>By combining sort() and reverse() you can sort an array in descending order.</p>
<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
// Create and display an array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
// First sort the array
fruits.sort();
// Then reverse it:
fruits.reverse();
document.getElementById("demo").innerHTML = fruits;
}
</script>

</body>
</html>

Parul Saxena, MITS 174


Logical Operators
<html>
<body>
<h2>JavaScript Comparison</h2>

<p>The AND operator (&&) returns true if both expressions are true, otherwise it returns
false.</p>
<p id="demo"></p>

<script>
var x = 6;
var y = 3;
document.getElementById("demo").innerHTML =
(x < 10 && y > 1) + "<br>" +
(x < 10 && y < 1);
</script>
</body>
</html>

Parul Saxena, MITS 175


<html>
<body>

<h2>JavaScript Comparison</h2>

<p>The OR operator (||) returns true if one or both expressions are true, otherwise it returns false.</p>

<p id="demo"></p>

<script>
var x = 6;
var y = 3;

document.getElementById("demo").innerHTML =
(x == 5 || y == 5) + "<br>" +
(x == 6 || y == 0) + "<br>" +
(x == 0 || y == 3) + "<br>" +
(x == 6 || y == 3);
</script>

</body>
</html>

Parul Saxena, MITS 176


<html>
<body>

<h2>JavaScript Comparison</h2>

<p>The NOT operator (!) returns true for false statements and false for true statements.</p>

<p id="demo"></p>

<script>
var x = 6;
var y = 3;

document.getElementById("demo").innerHTML =
!(x === y) + "<br>" +
!(x > y);
</script>

</body>
</html>

Parul Saxena, MITS 177


===equal value and equal type
Difference between Undefined and Null
• Undefined and null are equal in value but
different in type.
• typeof undefined // undefined
• typeof null // object

• null === undefined


// false
• null == undefined
// true
Parul Saxena, MITS 178
<html>
<body>

<h2>JavaScript Comparison</h2>

<p>Assign 5 to x, and display the value of the comparison (x ===


5):</p>

<p id="demo"></p>

<script>
var x = 5;
document.getElementById("demo").innerHTML = (x === 5);
</script>

</body>
</html>

Parul Saxena, MITS 179


<html>
<body>

<h2>JavaScript Comparison</h2>

<p>Assign 5 to x, and display the value of the comparison (x ===


"5").</p>

<p id="demo"></p>

<script>
var x = 5;
document.getElementById("demo").innerHTML = (x === "5");
</script>

</body>
</html>

Parul Saxena, MITS 180


Undefined

• In JavaScript, a variable without a value, has the


value undefined. The type is also undefined.
• Example
• var car; // Value is undefined, type is undefined

• Example
var car;
document.getElementById("demo").innerHTML = car + "<br>" + typeof car;

Parul Saxena, MITS 181


alert(typeof(null));
// object
alert(typeof(undefined));
// undefined
alert(null !== undefined)
//true
alert(null == undefined)
//true

Parul Saxena, MITS 182


Conditional (Ternary) Operator

• Syntax
variablename = (condition) ? value1:value2
• Example
var voteable = (age < 18) ? "Too young":"Old
enough";

Parul Saxena, MITS 183


<html>
<body>

<p>Input your age and click the button:</p>

<input id="age" value="18" />

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var age, voteable;
age = document.getElementById("age").value;
voteable = (age < 18) ? "Too young":"Old enough";
document.getElementById("demo").innerHTML = voteable + " to vote.";
}
</script>

</body>
</html>

Parul Saxena, MITS 184


Comparing Different Types
• When comparing a string with a number, JavaScript will convert the
string to a number when doing the comparison. An empty string
converts to 0. A non-numeric string converts to NaN which is
always false.
• Case Value
• 2 < 12 true
• 2 < "12“ true
• 2 < "John“ false
• 2 > "John“ false
• 2 == "John“ false
• "2" < "12“ false
• "2" > "12“ true
• "2" == "12“ false
• When comparing two strings, "2" will be greater than "12", because
(alphabetically) 1 is less than 2.

Parul Saxena, MITS 185


<html>
<body>

<h2>JavaScript Comparison</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 2 < "John";
</script>

</body>
</html>

Parul Saxena, MITS 186


<html>
<body>

<h2>JavaScript Comparison</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 2 == "John";
</script>

</body>
</html>

Parul Saxena, MITS 187


<html>
<body>

<h2>JavaScript Comparison</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "2" < "12";
</script>

</body>
</html>

Parul Saxena, MITS 188


<html>
<body>

<h2>JavaScript Comparison</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "2" > "12";
</script>

</body>
</html>

Parul Saxena, MITS 189


<html>
<body>

<h2>JavaScript Comparison</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "2" ==
"12";
</script>

</body>
</html>
Parul Saxena, MITS 190
• alert( 'Z' > 'A' ); // true
• alert( 'Glow' > 'Glee' ); // true
• alert( 'Bee' > 'Be' ); // true

Parul Saxena, MITS 191


<html>
<body>

<h2>JavaScript Comparisons</h2>

<p>Input your age and click the button:</p>

<input id="age" value="18" />

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var age, voteable;
age = Number(document.getElementById("age").value);
if (isNaN(age)) {
voteable = "Input is not a number";
} else {
voteable = (age < 18) ? "Too young" : "Old enough";
}
document.getElementById("demo").innerHTML = voteable;
}
</script>

</body>
</html>

Parul Saxena, MITS 192


Conditional Statements
In JavaScript we have the following conditional statements:
• Use if to specify a block of code to be executed, if a specified
condition is true
• Use else to specify a block of code to be executed, if the same
condition is false
• Use else if to specify a new condition to test, if the first
condition is false
• Use switch to specify many alternative blocks of code to be
executed

Parul Saxena, MITS 193


The if Statement
• Use the if statement to specify a block of
JavaScript code to be executed if a condition is
true.
• Syntax
• if (condition) {
// block of code to be executed if the condition is
true
}
• Note that if is in lowercase letters. Uppercase
letters (If or IF) will generate a JavaScript error.
Parul Saxena, MITS 194
The else Statement
• Use the else statement to specify a block of
code to be executed if the condition is false.
• if (condition) {
// block of code to be executed if the
condition is true
} else {
// block of code to be executed if the
condition is false
}

Parul Saxena, MITS 195


The else if Statement
• Use the else if statement to specify a new condition if
the first condition is false.
• Syntax
• if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is
false and condition2 is true
} else {
// block of code to be executed if the condition1 is
false and condition2 is false
}

Parul Saxena, MITS 196


<html>
<body>
<script type = "text/javascript">

var age = 20;

if( age > 18 ) {


document.write("<b>Qualifies for driving</b>");
}

</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Parul Saxena, MITS 197


<html>
<body>
<script type = "text/javascript">

var age = 15;

if( age > 18 ) {


document.write("<b>Qualifies for driving</b>");
} else {
document.write("<b>Does not qualify for driving</b>");
}

</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Parul Saxena, MITS 198


<html>
<body>
<script type = "text/javascript">

var book = "maths";


if( book == "history" ) {
document.write("<b>History Book</b>");
} else if( book == "maths" ) {
document.write("<b>Maths Book</b>");
} else if( book == "economics" ) {
document.write("<b>Economics Book</b>");
} else {
document.write("<b>Unknown Book</b>");
}

</script>
<p>Set the variable to different value and then try...</p>
</body>
<html>

Parul Saxena, MITS 199


The JavaScript Switch Statement
• Use the switch statement to select one of many code blocks to be executed.
• Syntax
• switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
• This is how it works:
– The switch expression is evaluated once.
– The value of the expression is compared with the values of each case.
– If there is a match, the associated block of code is executed.
– If there is no match, the default code block is executed.

Parul Saxena, MITS 200


<html>
<body>
<script type = "text/javascript">

var grade = 'A';


document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />");
break;

case 'B': document.write("Pretty good<br />");


break;

case 'C': document.write("Passed<br />");


break;

case 'D': document.write("Not so good<br />");


break;

case 'F': document.write("Failed<br />");


break;

default: document.write("Unknown grade<br />")


}
document.write("Exiting switch block");

</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Parul Saxena, MITS 201
The While Loop
• The while loop loops through a block of code
as long as a specified condition is true.
• Syntax
• while (condition) {
// code block to be executed
}

Parul Saxena, MITS 202


<html>
<body>

<h2>JavaScript While Loop</h2>

<p id="demo"></p>

<script>
var text = "";
var i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Parul Saxena, MITS 203


The Do/While Loop
• The do/while loop is a variant of the while loop.
This loop will execute the code block once, before
checking if the condition is true, then it will
repeat the loop as long as the condition is true.
• Syntax
• do {
// code block to be executed
}
while (condition);
Parul Saxena, MITS 204
<html>
<body>

<h2>JavaScript Do/While Loop</h2>

<p id="demo"></p>

<script>
var text = ""
var i = 0;

do {
text += "<br>The number is " + i;
i++;
}
while (i < 10);

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Parul Saxena, MITS 205


JavaScript Loops
• Loops are handy, if you want to run the same
code over and over again, each time with a
different value.
• JavaScript supports different kinds of loops:
– for - loops through a block of code a number of times
– for/in - loops through the properties of an object
– for/of - loops through the values of an iterable object
– while - loops through a block of code while a specified
condition is true
– do/while - also loops through a block of code while a
specified condition is true

Parul Saxena, MITS 206


The For Loop

• The for loop has the following syntax:


• for (statement 1; statement 2; statement 3) {
// code block to be executed
}

• Statement 1 is executed (one time) before the


execution of the code block.
• Statement 2 defines the condition for executing
the code block.
• Statement 3 is executed (every time) after the
code block has been executed.
Parul Saxena, MITS 207
<html>
<body>
<script type = "text/javascript">

var count;
document.write("Starting Loop" + "<br />");

for(count = 0; count < 10; count++) {


document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop stopped!");

</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Parul Saxena, MITS 208


The For/In Loop
The for...in loop is used to loop through an object's
properties.
• Syntax
• The syntax of ‘for..in’ loop is −
• for (variablename in object) {
statement or block to execute
}
• In each iteration, one property from object is
assigned to variablename and this loop continues
till all the properties of the object are exhausted.

Parul Saxena, MITS 209


<html>
<body>

<h2>JavaScript For/In Loop</h2>

<p>The for/in statement loops through the properties of an object.</p>

<p id="demo"></p>

<script>
var txt = "";
var person = {fname:"John", lname:"Doe", age:25};
var x;
for (x in person) {
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>

</body>
</html>

Parul Saxena, MITS 210


The For/Of Loop

• The JavaScript for/of statement loops through


the values of an iterable objects.
• The for/of loop has the following syntax:
• for (variable of iterable) {
// code block to be executed
}

Parul Saxena, MITS 211


<html>
<body>

<h2>JavaScript For/Of Loop</h2>

<p>The for/of statement loops through the values of an iterable object.</p>

<script>
var cars = ['BMW', 'Volvo', 'Mini'];
var x;

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

</body>
</html>

Parul Saxena, MITS 212


Looping over a String
<html>
<body>

<h2>JavaScript For/Of Loop</h2>

<p>The for/of statement loops through the values of an iterable object.</p>

<script>
var txt = 'JavaScript';
var x;

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

</body>
</html>

Parul Saxena, MITS 213


The Break Statement
• The break statement "jumps out" of a loop.
• The break statement breaks the loop and continues executing the code after the loop (if any)
<html>
<body>

<h2>JavaScript Loops</h2>

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

<p id="demo"></p>

<script>
var text = "";
var i;
for (i = 0; i < 10; i++) {
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Parul Saxena, MITS 214


The Continue Statement
• The continue statement breaks one iteration
(in the loop), if a specified condition occurs,
and continues with the next iteration in the
loop.
for (i = 0; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}

Parul Saxena, MITS 215


<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 = "";
var i;
for (i = 0; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Parul Saxena, MITS 216


JavaScript Labels
• To label JavaScript statements you precede the statements with a
label name and a colon:
• label:
statements
• The break and the continue statements are the only JavaScript
statements that can "jump out of" a code block.
• Syntax:
break labelname;
continue labelname;
• The continue statement (with or without a label reference) can only
be used to skip one loop iteration.
• The break statement, without a label reference, can only be used
to jump out of a loop or a switch.
• With a label reference, the break statement can be used to jump
out of any code block:
• A code block is a block of code between { and }.

Parul Saxena, MITS 217


<html>
<body>

<h2>JavaScript break</h2>

<p id="demo"></p>

<script>
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var text = "";

list: {
text += cars[0] + "<br>";
text += cars[1] + "<br>";
break list;
text += cars[2] + "<br>";
text += cars[3] + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Parul Saxena, MITS 218


<html>
<body>
<script type = "text/javascript">

document.write("Entering the loop!<br /> ");


outerloop: // This is the label name
for (var i = 0; i < 5; i++) {
document.write("Outerloop: " + i + "<br />");
innerloop:
for (var j = 0; j < 5; j++) {
if (j > 3 ) break ; // Quit the innermost loop
if (i == 2) break innerloop; // Do the same thing
if (i == 4) break outerloop; // Quit the outer loop
document.write("Innerloop: " + j + " <br />");
}
}
document.write("Exiting the loop!<br /> ");

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

Parul Saxena, MITS 219


<html>
<body>

<script type = "text/javascript">

document.write("Entering the loop!<br /> ");


outerloop: // This is the label name

for (var i = 0; i < 3; i++) {


document.write("Outerloop: " + i + "<br />");
for (var j = 0; j < 5; j++) {
if (j == 3) {
continue outerloop;
}
document.write("Innerloop: " + j + "<br />");
}
}

document.write("Exiting the loop!<br /> ");

</script>

</body>
</html>

Parul Saxena, MITS 220


typeof "John" // Returns "string"
typeof 3.14 // Returns "number"
typeof NaN // Returns "number"
typeof false // Returns "boolean"
typeof [1,2,3,4] // Returns "object"
typeof {name:'John', age:34} // Returns "object"
typeof function () {} // Returns "function"
typeof myCar // Returns "undefined" *
typeof null // Returns "object“
Number("3.14") // returns 3.14
Number(" ") // returns 0
Number("") // returns 0
Number("99 88") // returns NaN
Parul Saxena, MITS 221
<html>
<body>

<h2>The JavaScript typeof Operator</h2>

<p>The typeof operator returns the type of a variable, object, function or expression.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
typeof "john" + "<br>" +
typeof 3.14 + "<br>" +
typeof NaN + "<br>" +
typeof false + "<br>" +
typeof [1,2,3,4] + "<br>" +
typeof {name:'john', age:34} + "<br>" +
typeof function () {} + "<br>" +
typeof myCar + "<br>" +
typeof null;
</script>

</body>
</html>

Parul Saxena, MITS 222


• Please observe:
– The data type of NaN is number
– The data type of an array is object
– The data type of null is object
– The data type of an undefined variable
is undefined *
– The data type of a variable that has not been
assigned a value is also undefined *

Parul Saxena, MITS 223


The Unary + Operator
• The unary + operator can be used to convert a
variable to a number:
• Example
• var y = "5"; // y is a string
var x = + y; // x is a number

Parul Saxena, MITS 224


<html>
<body>

<h2>The JavaScript typeof Operator</h2>

<p>The typeof operator returns the type of a variable or expression.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var y = "5";
var x = + y;
document.getElementById("demo").innerHTML = typeof y + "<br>" + typeof x;
}
</script>

</body>
</html>

Parul Saxena, MITS 225


<html>
<body>

<h2>JavaScript Comparison</h2>

<p>Assign 5 to x, and display the value of the comparison (x === "5").</p>

<p id="demo"></p>

<script>
var x = 5;
document.getElementById("demo").innerHTML = (x === "5");
</script>

</body>
</html>
• Example
• var y = "John"; // y is a string
var x = + y; // x is a number (NaN)

Parul Saxena, MITS 226


<html>
<body>

<h2>The JavaScript typeof Operator</h2>

<p>The typeof operator returns the type of a variable or expression.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var y = "John";
var x = + y;
document.getElementById("demo").innerHTML = typeof y + "<br>" + typeof x;
}
</script>

</body>
</html>

Parul Saxena, MITS 227


Automatic Type Conversion
• When JavaScript tries to operate on a "wrong" data type, it will
try to convert the value to a "right" type.
• The result is not always what you expect:
• 5 + null // returns 5 because null is converted to 0
"5" + null // returns "5null" because null is converted to "null"
"5" + 2 // returns "52" because 2 is converted to "2"
"5" - 2 // returns 3 because "5" is converted to 5
"5" * "2" // returns 10 because "5" and "2" are converted to 5 and 2

Parul Saxena, MITS 228


<html>
<body>

<p id="demo"></p>

<script>
var x = [];
document.getElementById("demo").innerHTML =
(5 + null) + "<br>" +
("5" + null) + "<br>" +
("5" + 2) + "<br>" +
("5" - 2) + "<br>" +
("5" * "2") + "<br>" +
("5" / "2") + "<br>"
</script>

</body>
</html>

Parul Saxena, MITS 229


• input a number between 1 and 10
<html>
<body>
<h2>JavaScript Can Validate Input</h2>
<p>Please input a number between 1 and 10:</p>

<input type="text" id="numb">


<button type="button" onclick="myFunction()">Submit</button>

<p id="demo"></p>
<script>
function myFunction() {
var x, text;

// Get the value of the input field with id="numb"


x = document.getElementById("numb").value;
// If x is Not a Number or less than one or greater than 10
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>

Parul Saxena, MITS 230


The checkValidity() Method
• Returns true if an input element contains valid data.
• validationMessage - Contains the message a browser will display when the
validity is false.

<input id="id1" type="number" min="100" max="300" required>


<button onclick="myFunction()">OK</button>
<p id="demo"></p>
<script>
function myFunction() {
var inpObj = document.getElementById("id1");
if (!inpObj.checkValidity()) {
document.getElementById("demo").innerHTML =
inpObj.validationMessage;
}
}
</script>

Parul Saxena, MITS 231


<html>
<body>

<p>Enter a number and click OK:</p>

<input id="id1" type="number" min="100" max="300" required>


<button onclick="myFunction()">OK</button>

<p>If the number is less than 100 or greater than 300, an error message will be displayed.</p>

<p id="demo"></p>

<script>
function myFunction() {
var inpObj = document.getElementById("id1");
if (!inpObj.checkValidity()) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
} else {
document.getElementById("demo").innerHTML = "Input OK";
}
}
</script>

</body>
</html>

Parul Saxena, MITS 232


Differences between innerText,
innerHTML and textContent
• innerText returns: "This element has extra spacing and
contains a span element."
innerHTML returns: " This element has extra
spacing and contains <span>a span element</span>."
textContent returns: " This element has extra
spacing and contains a span element."
• The innerText property returns just the text, without
spacing and inner element tags.
• The innerHTML property returns the text, including all
spacing and inner element tags.
• The textContent property returns the text with spacing, but
without inner element tags.
// js5.html

Parul Saxena, MITS 233

You might also like