Chap-4 Javascript
Chap-4 Javascript
Chapter 4
JavaScript Programming
4.1. Introduction
JavaScript is used in millions of Web pages to improve the design, validate forms, detect
browsers, and much more. JavaScript is the most popular scripting language on the internet, and
works in all major browsers, such as Internet Explorer, Firefox, and Opera.
Scripting languages are usually interpreted rather than compiled. That means that a software
routine called an interpreter translate a program’s statements into machine code, code
understandable by a particular type of computer, before executing them every time the program
is run. Compiled languages, on the other hand, are translated into machine code and stored for
later execution. When the compiled program is run, it executes immediately without further need
of interpretation; it was interpreted into machine code when it was compiled. Because programs
written in interpreted languages must be translated into machine code every time they are run,
they are typically slower than compiled programs. However, this does not usually present a
problem for the small applications for which scripting languages are generally used.
Being interpreted does have its advantages. One is platform independence. Because an
interpreter performs the translation, we can write the program once and run it on a variety of
platforms. In the case of JavaScript, the interpreter is built into Web browsers. Browsers are
available for a variety of platforms and operating systems. Another advantage is that scripting
languages are often loosely typed and more forgiving than compiled languages.
4.2. Purposes of Java script :-
JavaScript gives HTML designers a programming tool - JavaScript is a scripting
language with a very simple syntax!
JavaScript can put dynamic text into an HTML page - A JavaScript statement like
this: [Link]("<h1>" + name + "</h1>") can write a variable text into an HTML
page
JavaScript can react to events - A JavaScript can be set to execute when something
happens, like when a page has finished loading or when a user clicks on an HTML
element
JavaScript can read and write HTML elements - A JavaScript can read and change the
content of an HTML element
JavaScript can be used to validate data - A JavaScript can be used to validate form
data before it is submitted to a server. This saves the server from extra processing
Page 1 of 25
web Programming – Lecture Note chapter-4
4.3. Running the JavaScript
Any time including JavaScript in an HTML document, we must enclose those lines inside a
<SCRIPT>...</SCRIPT> tag pair. These tags alert the browser program to begin interpreting all
the text between these tags as a script. Because other scripting languages (such as Microsoft’s
VBScript) can take advantage of these script tags, we must specify the precise name of the
language in which the enclosed code is written. Therefore, when the browser receives this signal
that our script uses the JavaScript language, it employs its built-in JavaScript interpreter to
handle the code.
JavaScript is case-sensitive. Hence, we must enter any item in our script that uses a JavaScript
word with the correct uppercase and lowercase letters. HTML tags (including the <SCRIPT>
tag) can be in the case of our choice, but everything in JavaScript is case-sensitive. JavaScript
should be put between the following:-
<SCRIPT LANGUAGE=”JavaScript”>
//your script here
</SCRIPT>
Or
<SCRIPT type=”text/JavaScript”>
//your script here
</SCRIPT>
As shown above, the attribute name called LANGUAGE & TYPE can be used interchangeably.
But, commonly we use type attribute.
Here are some tips to remember when writing JavaScript commands:
JavaScript code is case sensitive (e.g. age and Age are different variables)
White space between words and tabs are ignored
Line breaks are ignored except within a statement
JavaScript statements end with a semi colon (;) but not always
JavaScript can come at different places. There is a flexibility given to include JavaScript code
anywhere in an HTML document. But, the following are the most preferred ways to include
JavaScript in an HTML file.
Script in <head>...</head> section.
Script in <body>...</body> section.
Script in both<body>...</body> and <head>...</head> sections.
Script in and external file and then include in <head>...</head> section.
Page 2 of 25
web Programming – Lecture Note chapter-4
Wherever we use/ define a JavaScript block in our web page, simply use the following block
of HTML.
<script type=”text/JavaScript”>
// Your script goes here.
</script>
We can place these script blocks anywhere on the page that we wish, there are some rules
and conventions however.
But, for external external File, use the SRC attribute of the <SCRIPT> tag to call JavaScript
code from an external text file.
This is useful if we have a lot of code or we want to run it from several pages, because any
number of pages can call the same external JavaScript file. The text file itself contains no
HTML tags. It is called by the following tag:
<SCRIPT type = "JavaScript" SRC = " url of javascript file">
</SCRIPT>
If we want to run the same JavaScript on several pages, without having to write the same
script on every page, we can write a JavaScript in an external file. Save the external
JavaScript file with a .js file extension. The external script cannot contain the <script>
</script> tags. To use the external script, point to the .js file in the "src" attribute of the
<script> tag.
JavaScript is put in a page where it will be executed immediately while the page loads into
the browser. Sometimes we want to execute a script when a page loads, or at a later event,
such as when a user clicks a button.
Script between <head>…..</head>
If we need to place our script in header of the html document like the following.
<html>
<head>
<script language="javascript">
[Link](“Welcome to Java script”);
</script>
</head>
<body>
</body>
</html>
Scripts in <body>…..</body> tags
Page 3 of 25
web Programming – Lecture Note chapter-4
If we don't want our script to be placed inside a function, or if our script should write page
content, it should be placed in the body section.
<html>
<head> </head>
<body>
<script language="javascript">
[Link]("This message is written by JavaScript");
</script>
</body>
</html>
Page 4 of 25
web Programming – Lecture Note chapter-4
</head>
<body onload="message()">
<br><br><br><br><br><br>
<h1>I THANK YOU FOR EVERY THING YOU MADE!!!</H1>
</body>
</html>
Prompt box:- is used to allow a user to enter something according to the promotion. It is
written as [Link]("please enter your name") or simply write as prompt(“some
text”)
Example:-
<script>
var y=[Link]("please enter your name")
[Link](y)
</script>
Confirm Box:- A confirm box is often used if we want the user to verify or accept
something. When a confirm box pops up, the user will have to click either "OK" or "Cancel"
to proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false. It has the following Syntax [Link]("sometext"); or simply write
confirm(“some text”)
Example :-
<script type=”text/javascript”>
var x=window. confirm("Are you sure you want to quit");
if (x)
{
[Link]("Thank you.")
x="You pressed OK!";
}
else
{
[Link]("Good choice.")
x="You pressed Cancel!";
}
[Link] (x);
</script>
Page 5 of 25
web Programming – Lecture Note chapter-4
The Page Printing:- JavaScript helps us to implement this functionality using print function
of window object. The JavaScript print function [Link]() will print the current web
page when executed. We can call this function directly using onclick event as follows:
<html>
<head>
<script type="text/javascript">
</script>
</head>
<body>
<form>
<input type="button" value="Print" onclick="[Link]()">
</form>
</body>
</html>
4.5. Working with Variables and Data
In JavaScript, a value can be one of several types as shown bellow:-
Type Example Description
String “John” a series of characters inside quotation marks
Number 4.5 any number not inside quotes
Boolean True a logical true or false
Null Null completely devoid of any value
Object a software thing that is defined by its properties and
methods
Table JavaScript data types
i. Declaring Variables
To declare variable, we use the var keyword, followed by the name we want to give to the
variable. JavaScript variables can be declared with the var keyword as var variablename;
To declare a new variable called myAge, the JavaScript statement is var myAge;
Variable names obey number of restrictions (rules).
Don’t use any reserved keyword as a variable name.
A variable name cannot contain space characters. Therefore, one-word variable names are fine. For
example, the followings are invalid:- var my age; var my Age;
Variable names should avoid all punctuation symbols except for the underscore character. Also, the
first character of a variable name cannot be a numeral.
Page 6 of 25
web Programming – Lecture Note chapter-4
To put together, a variable name can contain letters of the alphabet, both capital and small, number
and _ (underscore). Still, the name should start with letters of the alphabet, or _, not digits
Example: see the following correct variable declaration,
var firstName;
var he89;
var TH_;
Example: Wrong variable names:
var first name; //space not allowed
var 89he; //can’t start with digit
var TH.; //punctuation mark not allowed
ii. Assigning Values to Variables
After the declaration shown above, the variables are empty which means they have no data
values yet. After declaring a variable, it is possible to assign a value to it by using equal sign
(=) as follows:
var myAge;
myAge = 25;
However, we can also assign values to the variables as: var age=5;
[Link] Values to Undeclared Variables
To assign values to variables that have not yet been declared, the variables will
automatically be declared. These statements:
age=5;
The above statements have the same effect as:
var age=5;
iv. Re-declaring JavaScript Variables
If we redeclare a JavaScript variable, it will not lose its original value.
var age=5;
var age;
After the execution of the statements above, the variable age will still have the value of 5.
The value of age is not reset (or cleared) when we redeclare it.
v. Comments JavaScript supports two types of comments:
Comments on a single line are preceded by a double-slash (//).
Comments that span multiple lines are preceded by /* and followed by */
Page 7 of 25
web Programming – Lecture Note chapter-4
4.6. Operators and Expressions
An operator performs some kind of calculation (operation) or comparison with two values to
reach a third value. Generally, operators can be broadly categorized into two: mathematical
operators, and comparison and logical operators.
i. Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations between variables or values. +, -,
*, /, %, ++, --
ii. JavaScript Assignment Operators
Assignment operators are used to perform arithmetic operation and then assign the result to
variables. Includes:- =, +=, -=, *=, /= and %=
iii. Comparison Operators
Comparison operators help to compare two or more values — whether two values are equal, for
example. These kinds of comparisons return a value of the Boolean type — true or false.
Includes:- >, >=, <, <=, = =, and !=
iv. Logical Operators
Logical operators are used to determine the logic between variables or values:- &&, ||
4.7. Java Script Statements
A. Working with Conditional Statements
Conditional statements are used to perform different actions based on different conditions.
Broadly, there are two ways to execute code conditionally:
If statement
switch statement
i. If condition/if -----else condition:- The simplest program decision is to follow a special
branch or path of the program if a certain condition is true. Formal syntax for this
construction follows:
if (condition) {
statement[s] if true
}
If the condition evaluates to true, then one or more statements inside the curly braces execute
before continuing on with the next statement after the closing brace. If the condition evaluates to
false, then the statements inside the curly brace are ignored and processing continues with the
next statement after the closing brace.
The formal syntax definition for an if...else construction is as follows:
if (condition) {
statement(s) if true
Page 8 of 25
web Programming – Lecture Note chapter-4
}
[else if(condition){
statement(s) if true
}]
[else {
statement(s) if false
}]
Where [ ] indicates optional parts of the JavaScript code.
Page 9 of 25
web Programming – Lecture Note chapter-4
Example:-
<script type="text/javascript">
var book = "maths";
if( book == "history" ){
[Link]("<b>History Book</b>");
}else if( book == "maths" ){
[Link]("<b>Maths Book</b>");
}else{
[Link]("<b>Unknown Book</b>");}
</script>
ii. Switch Statement:- A switch statement allows a program to evaluate an expression and attempt
to match the expression's value to a case label. If a match is found, the program executes the
associated statement. A switch statement looks as follows:
switch (expression) {
case label1:
statements1
[break;]
case label2:
statements2
[break;]
...
default:
statementsdefault
[break;]
}
The program first looks for a case clause with a label matching the value of expression. If found, it
then transfers control to that clause, executing the associated statements. If no matching label is
found, the program looks for the optional default clause. If no default clause is found, the program
continues execution at the statement following the end of switch. By convention, the default clause
is the last clause.
If break is omitted, the program continues execution at the next statement in the switch statement
when there is a matched statement.
Example:-
<script type="text/javascript">
Page 10 of 25
web Programming – Lecture Note chapter-4
var grade='A';
[Link]("Entering switch block<br />");
switch (grade)
{
case 'A': [Link]("Good job<br />");
case 'B': [Link]("Pretty good<br />");
case 'C': [Link]("Passed<br />");
case 'D': [Link]("Not so good<br />");
case 'F': [Link]("Failed<br />");
default: [Link]("Unknown grade<br />")
}
[Link]("Exiting switch block");
</script>
Page 11 of 25
web Programming – Lecture Note chapter-4
</html>
ii. do...while Statement
The do...while statement repeats until a specified condition evaluates to false. A do...while
statement is written as follows:
do{
statement
}while (condition);
statement executes once before the condition is checked. If condition is true, the statement executes
again. At the end of every execution, the condition is checked. When the condition is false,
execution stops and control passes to the statement following do...while.
Example: the do loop iterates at least once and reiterates until i is no longer less than 5.
i=1;
do
{
i + = 1;
[Link] (i);
} while (i < 5);
Page 12 of 25
web Programming – Lecture Note chapter-4
i=i+1;
}
</script>
<i>Thank you being understand me</i>
</body>
</html>
iv. Break and continue statements:-
These are used to come out of a loop without reaching at its bottom or to skip a part of the code
block and want to start next iteration of the look when needed by users or programmers.
To handle all such situations, JavaScript provides break and continue statements. These statements
are used to immediately come out of any loop or to start the next iteration of any loop.
Example1: the following example loops until the value of loop counter is 5:
for (i = 0; i < 100; i++) {
if (i= = 5)
break;
}
The continue statement can be used to restart a while, do-while or for statement. When we use
continue, it terminates the current iteration and continues execution of the loop with the next
iteration. In contrast to the break statement, continue does not terminate the execution of the loop
entirely. In a while loop, it jumps back to the condition check, and in for loop, it jumps to the
increment-expression. But, break statement is used to terminate loop.
Example 2: a program that adds numbers between 0 and 100 with the exception of 60, 70, and 80
<script type=”text/javascript”>
var counter = 100, sum = 0;
for (var i = 0; i <= counter; i++)
{ if(i==60 || i==70 || i==80)
continue;
sum = sum + i;
}
[Link](“the sum is ” + sum);
</script>
C. Using Arrays
An array is an ordered collection of data. In JavaScript, arrays are limited to a table holding one
column of data, with as many rows as needed to hold data.
Page 13 of 25
web Programming – Lecture Note chapter-4
A JavaScript-enabled browser creates a number of internal arrays for the objects in HTML
documents and browser properties. For example, if our document contains five links, the browser
maintains a table of those links. To access them by number (with 0 being the first link) in the array
syntax as in [Link][0], which represents the first link in the document.
To initialize an array for script, use the new keyword to construct the object for assigning the
array object to a variable of our choice like:
var myArray = new Array(n) where n is the number of entries anticipated for the array.
This initialization does not make any array entries or create any placeholders.
Example: an array that stores the names of planets
planet = new Array(9); //an array with 9 entries
planet[0] = “Mercury” planet[5] = “Saturn”
planet[1] = “Venus” planet[6] = “Uranus”
planet[2] = “Earth” planet[7] = “Neptune”
planet[3] = “Mars” planet[8] = “Pluto”
planet[4] = “Jupiter”
The index number starts at 0 and end at n-1 for array of n entries to access them. For example,
to access the fifth planet in the planets array, we use: planet[4]; //Jupiter
To deleting array entries, we can always set the value of an array entry to null or an empty
string to wipe out any data that used to occupy that space. But with the delete operator, we
could not completely remove the element. Deleting an array element eliminates the index from
the list of accessible index values but does not reduce the array’s length.
[Link]; // result: 9
delete planet[2];
[Link]; //result: 9
planet[2]; //result: undefined
o [Link](array2):- The [Link]() method allows to join two array objects into a new
array object. The action of concatenating the arrays does not alter the contents or behavior of the
two original arrays.
For example:
var array1 = new Array(1,2,3)
var array2 = new Array(“a”,”b”,”c”)
var array3 = [Link](array2) // result: array with values 1,2,3,”a”,”b”,”c”
Page 14 of 25
web Programming – Lecture Note chapter-4
If an array element is a string or number value (not a string or number object), the values are copied
from the original arrays into the new one. All connection with the original arrays ceases for those
items.
Page 15 of 25
Example 4:- on push
<html> var length = [Link](10);
<head> [Link]("new numbers is : " + numbers );
<title>JavaScript Array push Method</title> length = [Link](20);
</head> [Link]("<br />new numbers is : " +
<body> numbers );
<script type="text/javascript"> </script>
var numbers = new Array(1, 4, 9); </body>
</html>
[Link] = </form>
} </html>