Unit-III
Unit – 3
Features of javascript
• Imperative and structured - Javascript supports all the syntaxes of the programming
language C, such as the if statement, loops, and the switch statement. The only
difference between C and Javascript is in Javascript semicolon is not necessary to
terminate a statement, whereas in C, semicolon is necessary to terminate a
statement.
• Dynamic text – javascript supports dynamic typing. This means that the type of
variable is defined according to the value stored in it.
• Functional – implies that Javascript does not support classes. Instead of using classes,
objects are created from the constructor functions.
• Prototype-based – implies that javascript is a prototype based scripting language.
• Platform independent – implies that Javascript supports platform independency. This
means that you can write the script once and run it anywhere at any time.
-----------*-------------
Using Javascript in an HTML Document
You can insert Javascript code in an HTML document by using the SCRIPT element.
When an HTML document with the SCRIPT element is loaded in a web browser the browser
processes the content enclosed within the SCRIPT element. The SCRIPT element contains five
attributes: async, type, charset, defer and src.
You can use the SCRIPT element in a web page in the following three ways:
• In the HEAD element
• In the BODY element
• As an external script file
Javascript in the HEAD Element
You can place the SCRIPT element inside the HEAD element of an HTML document. The
scipt placed inside the HEAD element runs when you perform some action, such as click a link
or the submit button.
<HEAD>
<SCRIPT type=”text/Javascript”>
Script code here
Page No. : 1
Unit-III
</SCRIPT>
</HEAD>
Javascript in the BODY Element
You can also place the SCRIPT element inside the BODY element of an HTML document.
The SCRIPT element placed inside the BODY element runs when a Web page starts loading in a
Web browser.
<BODY>
<SCRIPT type=”text/Javascript”>
Script code here
</SCRIPT>
</BODY>
Javascript in an External File
When the Javascript code created in an HTML document is very lengthy it affects the
readability of the HTML document. In such cases you can store the Javascript code in an
external file and save that file using the .js extension.
<HEAD>
<SCRIPT src=”URL of the External file”>
Script code here
</SCRIPT>
</HEAD>
-----------*-------------
Lexical Structure of Javascript
The lexical structure of Javascript provides the set of rules to write programs. It defines
rules for variable names, characters used for creating comments. The lexical structure defines
the following:
• Character set
• Case sensitivity
Page No. : 2
Unit-III
• White spaces and line breaks
• Optional semicolons
• Comments
• Literals
• Identifiers
• Reserved words
Understanding Character Sets
Character set is a set of characters reserved to write Javascript programs.
Special characters
Symbols Names
\t represents a tab
\f represents a form feed
\b represents a backspace
\n represents a new line
\r represents a carriage return
Understanding case sensitivity
Javascript is a case sensitive language, which means that keywords, variable names , function
names and identifiers should be consistent casing of letters. For example function is a keyword
that must always be written in lowercase.
Function MyFirstFunction()
//some code here
The preceding code generates an error because the keyword is not typed in lowercase.
Understanding White Spaces and Line breaks
Page No. : 3
Unit-III
The Javascript interpreter ignores tabs, spaces and newlines that appear in a program
except strings and regular expressions. For example the following code shows two different
functions that interpret the same variables:
function fun()
var i = 10;
var j = 20;
function fun1() { var i=10; var i=20; }
in the above code both the functions works in same manner.
Understanding the Optional Semicolon
The syntax of Javascript is similar to the syntax of C, C++ and Java. However it is not
necessary to use the semicolon at the end of the statement.
var var_name= value;
var var-name= value
Both the statement are valid.
Understanding comments
Comments refer to the text or code in a program that is ignored at the time of executing
the program. They are used to provide additional information.
• Single line comment – Starts with // and ends with the end of line
• Multi-line comment – Starts with the /* and ends with */.
Ex:
//single-line comment
/*multi-line
Comment*/
Understanding Literals
Page No. : 4
Unit-III
A literal is a data value that represents a fixed value in a program. Javascript supports
the following types of literals:
• Numeric literal
• Floating-point literal
• Boolean literal
• String literal
• Array literal
• Regular expression literal
• Object literal
The Numeric Literal
A numeric literals can be expressed in the decimal , hexadecimal and octal. Decimal
numeric literals consist of a sequence of digits(0-9), without a leading 0. Hexadecimal numeric
literals include digits(0-9) and the letters a-f and A-F.
89, 569 //decimal
021,065 //octal
0x5673 // hexadecimal
The Floating point literal
A floating point literal can have the following parts:
• A decimal integer that can be positive or negative
• A decimal point
• A fraction
• An exponent
Ex:
4.89080
-123.56734
0.98764563
The Boolean literal
The Boolean literal is used to make a decision in a relational expression. There are only
two Boolean literal values: true and false.
Page No. : 5
Unit-III
var b= true;
var c= false;
if(b=true)
//some code
The String Literal
A string literal can be a zero or more characters enclosed in double(“) or single(‘)
quotation.
“anuj”
‘charu’
“1234”
The array literal
An array literal is a list of zero or more expressions representing array elements that are
enclosed in square brackets([]).
var emp[“anuj”, “charu”, “suchita”];
Understanding identifiers:
Identifiers refer to the names given to all the components such as variables, and
metgods of a Javascript program.
• Identifiers must start with a letter, dollar sign or underscore.
• Identifiers cannot start with a number.
• Identifiers can contain any combination of letters, dollar sign, underscore and numbers
after the first character.
• Identifiers can be of any length
• Identifiers are case sensitive.
• Identifiers cannot contain reserved words or keywords.
Ex:
Page No. : 6
Unit-III
Valid identifiers
Sum
_abc
$_12
One_two
Invalid Indentifiers
-book
var
“count”
7g
-----------*-------------
Exploring Variables
In javascript data can be temporarily stored in variables, which are the named locations
in the memory. A variable has a name, value and memory address. The name of the variable
uniquely identifies the variable, the value refers to the data that is stored in the variable and
the memory address refers to the memory location of the variable. The syntax is used to
declare a variable.
var variable_name;
In the preceding syntax, var is a keyword and variable_name represents the name of the
variable. You can also declare multiple variables in the same statement.
var variable1, variable2, variable3
in the preceding syntax we have declared three variables named variable1, variable2
and variable3 by using the var keyword.
The syntax to assign a value to a variable at the time of decaration is as follows:
var variable_name= value;
Page No. : 7
Unit-III
the following syntax shows how to declare and assign a value to a variable:
var variable_name;
variable_name= value;
-----------*-------------
Exploring Operators
An operator is a symbol or word that is reserved for a special task or action. Every
operator works on one or more operands. After taking the values it performs an action on the
operands and returns the result of that action.
Table declares the list of operators
Operator Description Example
Arithmetic Operators
+ Adds two numbers of joins two 45+10
strings. Returns 55
- Subtracts two numbers or -45+10
represents a negative value Returns -35
* Multiplies two numbers 45*10
Returns 450
/ Divides two numbers and return the 45/10
quotient Returns 4.5
% Divides two numbers and returns 45%10
the remainder Returns 5
++ Increments the value of a number myVar1=45
by [Link] can be prefixed or
suffixed. When prefixed the value is myvar2=++myVar1
incremented in the current assigns 46 to myVar2
statement and when suffixed the myVar2=myVar1++
value is incremented after the assigns 45 to myVar2
current statement
-- Decrements the value of a number myVar1=45
by [Link] can be prefixed or
suffixed. When prefixed the value is myvar2=--myVar1
decremented in the current assigns 44 to myVar2
statement and when suffixed the myVar2=myVar1--
value is decremented after the assigns 45 to myVar2
current statement
Assignment Operators
Page No. : 8
Unit-III
= Assigns the value to the left hand myVar=90
side variable
+= Adds the right hand side operand to myVar1=45, myvar2=10
the left hand side operand and myvar1+=myVar2
assigns the result to the left hand assigns 55 to myVar1
side operand
-= Subtracts the right hand side myVar1=45, myvar2=10
operand from the left hand side myvar1-=myVar2
operand and assigns the result to assigns 35 to myVar1
the left hand side operand
*= Multiplies the right hand side myVar1=45, myvar2=10
operand with the left hand side myvar1*=myVar2
operand and assigns the result to assigns 450 to myVar1
the left hand side operand
/= Divides the left hand side operand myVar1=45, myvar2=10
by the right hand side operand and myvar1/=myVar2
assigns the quotient to the left hand assigns 4.5 to myVar1
side operand
%= Divides the left hand side operand myVar1=45, myvar2=10
by the right hand side operand and myvar1%=myVar2
assigns the remainder to the left assigns 5 to myVar1
hand side operand
Comparison Operators
== Returns true if the both the 45==10
operands are equal otherwise it Returns false
returns false
!= Returns true if the both the 45!=10
operands are not equal otherwise it Returns true
returns false
> Returns true if the left side operand 45>10
is greater than the right hand side Returns true
operand otherwise it returns false
>= Returns true if the left side operand 45>=10
is greater than or equal to the right Returns true
hand side operand otherwise it
returns false
< Returns true if the left side operand 45<10
is less than the right hand side Returns false
operand otherwise it returns false
<= Returns true if the left side operand 45<=10
is less than or equal to the right Returns false
hand side operand otherwise it
returns false
Page No. : 9
Unit-III
Logical operators
&& Returns true only if both the True&&false
operands are true otherwise it Returns false
returns false
|| Returns true only if either of the True || false
operands is true. It returns false Returns true
when both the operands are false
! Negates the operand, that is returns !true
true if the operand is false and Returns false
returns false if the operand is true
Conditional Operator
?: Returns the second operand if the myVar1=45, myVar2=10
first operand is true. However if the myResult=(myVar1<myVar2)?myVar1:myVar2
first operand is false it returns the returns 10
third operand
-----------*-------------
Exploring Control flow Statements
In javascript control flow statements are divided in to the following categories
• Selection Statements – allow the execution of a group of statements from multiple
groups of statements
• Loops – allows repeated execution of a group of statements
• Jump statements – allow the execution to skip or jump over certain statements
Selection statements
Selection statements use a condition to select or determine the statements that are to
be executed. These statements help you to make decisions and change the flow of execution of
the statements. In javascript there are three selection statements:
➢ If
➢ If..else
➢ Switch
The if statement
You can use the if statement when you want to excute a group of one or more script
statements only when a particular condition is met.
Syntax:
Page No. : 10
Unit-III
if(condition)
statement1
If the condition evaluates to true then the script statement represented by statement1
enclosed the curly braces is executed. If the condition evaluates to false, then the statement
enclosed within the curly braces is skipped and the statement immediately after the curly brace
is executed.
The if..else statement
The if statement allows you to execute a set of statements only when a particular
condition is true. However if you want to execute another set of statements when the condition
is false then you can use the if..else statement.
Syntax:
if
statement1
else
statement2
If the condition is true then the group of statements represented by statement1 enclosed
within the first curly braces is executed. If the condition is false then the statement1 is skipped
and the group of statements represented by statement2 of the else block is executed.
The switch statement
A switch statement is used to select a particular group of statements to be executed
among several groups of statements.
Page No. : 11
Unit-III
Syntax:
switch(expression)
case value1:statement1
break;
case value2:statement2
break;
case value3:statement3
break;
default:statement_default
break;
In a switch statement the expression to be evaluated is specified within parenthesis. The
expression is checked against each of the case values specified in the case statements. If any of
the case values match the value of the expression the group of statements(statement1,
statement2 or statement3) specified in the respective case statement is executed. If none of
the case values matches the value of the expression then the default statement is executed.
Loops statement
Loops statements are control flow statements that allow you to execute a particular
group of statements repeatedly. The number of times a group of statements is executed
depends on a particular condition that is a Boolean expression.
In javascript you can use any of the following three loops:
➢ while loop
➢ do..while loop
➢ for loop
the while loop
Page No. : 12
Unit-III
you can use the while loop when you want to check the condition at the start of the
loop. If the condition is false in the first iteration itself, the group of statements in the while
loop is never executed. On the other hand the group of statements keeps on executing until the
condition becomes false.
Syntax:
while(condition)
statement;
while is a keyword. The condition for the while loop is specified in parenthesis and the group of
statements is specified within the curly braces.
The do..while loop
If you want the group of statements to execute at least once even if the condition is
false then you can use the do..while loop. This is possible because the do..while loop is placed
at the end of the loop.
Syntax:
do
statement1
while(condition);
do and while are keywords. The group of statements represented by statement1 is
enclosed within curly braces.
The for loop
The for loop allows you to execute a group of statements for predetermined number of
times. The condition of the for loop is placed at the beginning of the loop.
Syntax:
Page No. : 13
Unit-III
for (initialization_statement; condition; updation_statement)
statement;
The initialization statement refers to the statement in which the loop control variable is
declared or assigned an initial value. Condition and updation statement to control the
execution of the for loop.
Jump statement
Jump statements allow you to jump over or skip certain statements in a script and
execute some other statements. You can use jump statements to exit or break a loop. In
Javascript there are two jump statements:
➢ break statement
➢ continue statement
The break statement
The break statement allows you to break or exit a loop. When used inside a loop the
break statement stops executing the loop and causes the loop to be immediately exited. If the
loop has statements after the break statement those statements are not executed.
The continue statement
Similar to the break statement the continue statement can also be used to stop the
execution of a loop. However the continue statement does not exit the loop; it excutes the
condition for the next iteration of the loop. If the loop has any statement after the continue
statement then those statements are skipped.
Note : Write a example program for this conditional
statements question already we have discussed in the class
-----------*-------------
Popup boxes
A popup box is a window that displays a message along with an OK button. The popup
box may also contain a cancel button. Javascript supports three types of popup boxes
Page No. : 14
Unit-III
➢ the alert box
➢ the confirm box
➢ the prompt box
The alert box
The alert box is generally used to display an alert message while executing the javascript
code. An alert box is used to display error messages after you validate a form. The alert box
contains an OK button, which the user has to click to continue with the execution of the code.
The confirm box
It is used to display a message as well as return a true or false value. The confirm box
displays a dialog box with two buttons, OK and Cancel. When you click the OK button, the
confirm box returns a true value and when you click the Cancel button the confirm box returns
a false value.
The prompt box
The prompt box is used to input a value from a user. It contains a text box and OK and
cancel buttons. The user has to click either the OK or Cancel button to continue the execution
of the code after entering an input value. If the user clicks the OK button the input value is
returned. Otherwise the box returns null value.
Note : Write a example program for this popup boxes
question already we have discussed in the class
Functions
A function is a collection of statements that is excuted when it is called at some point in
a program. A function performs a specific task within a program independent of the rest of the
code in the program. The javascript functions are divided in to the following two categories:
➢ functions without parameters – does not contain parameters. The code written in these
function is static, that the values of members of these functions cannot be changed at
runtime.
➢ Functions with parameters – contains parameters in its parenthesis such as integer and
string.
Page No. : 15
Unit-III
Built in functions
Function description
alert() displays information in a message box.
prompt() displays a message box consisting of the OK and cancel buttons.
isFinite() returns a Boolean value true or false
Defining and invoking a function
A function contains code that is executed when an event is triggered or the function is
called. You can call the function from anywhere within a program. You can also define
parameters to be passed with functions while calling the function. The parameters in a function
are used to exchange the information between a calling statement and function.
Syntax:
function function_name(parameter_name1, Parameter_name2)
//block of code
In the preceding syntax function_name represents the name of the function and it is followed
by a pair of parentheses. The parameter_name1, parameter_name2 are the name of the
parameters. A function can have any number of parameters. The block of code within the curly
braces will be executed when the function is called.
Syntax:
function_name(parameter_value1, parameter_value2…parameter_valueN)
Defining Function arguments
Arguments are the values passed to the function while calling it. It is important to note
that the number and order of arguments passed in the function call should match with the
number and order of arguments that you define in the function.
Syntax:
function_name(arg1, arg2,….argN)
Page No. : 16
Unit-III
Defining a return statement
A return statement specifies the value that is returned from a function. If you define a
function that return some value then the function must have the return statement.
Syntax:
return value;
Defining function scope and closures
A scope refers to an area within which a function and its variables are accessible.
Global – specifies that a function can be called or accessed from anywhere on a program
Local – specifies that a function can be accessed only within its parent function.
Calling functions with timer
➢ The setTimeout() method – executed code at specific interval
settimeout(function, delayTime)
➢ The clearTimeout() method – deactivates or cancels the timer that is set using the
setTimeout() method.
clearTimeout(timer)
➢ The setInterval() method – executes a function after a specified interval
setInterval(function, intervalTime)
➢ The clearInterval() method – deactivates or cancels the timer that is set using the
setInterval() method.
clearInterval(timer)
Note : Write a example program for this function question
already we have discussed in the class
-----------*-------------
Page No. : 17
Unit-III
Events
Events refer to actions that are detected by a programming language when you perform
a particular task. For example onclick event is detected by the programming language when you
click the mouse button.
Ex:
onevent = “code to handle the event”
Event Description
Onsubmit triggers on submitting a form
Onselect triggers on selecting an element
Oninvalid triggers when an element is invalid
Oninput triggers when input is provided for an element
Onforminput triggers when input is provided on a form
Onformchange triggers when a form change
Onfocus triggers when window gets focus
Oncontextmenu triggers when context menu is used
Onchange triggers when element changes
Onblur triggers when a window loses focus
Note : Write a example program for this events question
already we have discussed in the class
-----------*-------------
Objects
In javascript you can create a object in two ways either by creating a direct instance or
by creating an object using a function template. A direct instance of an object is created by
using the new keyword.
Page No. : 18
Unit-III
Syntax
Obj=new object();
You can also add property and methods by using a period(.) followed by a property or method
name
[Link]=”Robert”;
[Link]=32;
[Link]();
Obj is the newly created object; whereas name and rollnumber are its properties and
getValue() is its method.
A function template for an object is created by using the function keyword. You can also
add properties to the function template by using the this keyword.
Syntax
function bike(speed, engine, color)
[Link]=speed;
[Link]=engine;
[Link]=color;
Properties of an object
Property also known as the characteristics of an object. For example vehicle is an object
and color and speed are its properties. You can add properties to an object by using the this
keyword followed by the dot(.) operator.
function myobject(parameter)
this.property1=parameter
this.property2=”hello world”
Page No. : 19
Unit-III
<SCRIPT>
var object=new myobject(“Hello all”)
alert(object.property1)
[Link](object.property2)
</SCRIPT>
Methods of an object
A method is a set of one or more statements that are executed by referring the name of the
method. To add methods to a user defined object you need to perform the following steps:
➢ Declaring and defining a function for each method
➢ Associating a function with an object
Ex:
function computearea()
var area=[Link]=*[Link]*0.5
return area
<script type=”text/javascript”>
[Link](b,a){
[Link]=b;
[Link]=a;
[Link]=computearea
</script>
Page No. : 20
Unit-III
<script type=”text/javascript”>
var mytriangle=new triangle (20,10)
alert(“area=”+[Link]())
</script>
-----------*-------------
Builtin Javascript Objects
Javascript supports seven builtin objects which are String, Regexp, Boolean, Number, array, mth
and date.
The String Object
A string is a sequence of characters. All strings are represented as instances of the string
object.
Properties of String Object
Property Description
constructor returns the function
length returns the length of a string
prototype adds properties and methods to an object
Methods of the String Object
Method Description
charAt() returns the character in the specified index
charCodeAt() returns the Unicode equivalence of the character
concat() joins two strings and returns the joint string
fromCharCode() converts Unicode to character
indexOf() returns the position of the first occurrence of the specified
character
replace() searches the regular expression and a string and replaces the
matched string with a new substring
Page No. : 21
Unit-III
split() splits a string into substrings
The Boolean object
A Boolean object is a wrapper class and a member of global objects. It is used to convert
the non Boolean values into Boolean values. It has two values: true and false. The Boolean
value returns false when the object is passed with values such as 0, “”, false, null, undefined
and Not a Number values.
Using Boolean literals
Boolean literals make use of two keywords, true and false.
var bool=true;
The value of the bool variable has been set to true.
[Link](bool + “ “);
Using Boolean object as function
Boolean objects are used to pass the desired initial value as an argument.
var bool=Boolean(false);
The Array object
The array object is used to store multiple values in a single variable.
Using the array constructor
An empty array is created in cases where you do not know the exact number of
elements to be inserted in an array.
var myarray = new array();
the following code is used to create an array of any given size
var myarray= new array(20);
-----------*-------------
Page No. : 22
Unit-III
Note : study the DHTML question already we have discussed
in the class
Page No. : 23