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

JavaScript-JS

This document provides an overview of JavaScript, covering its basics, origins, uses, and differences from Java. It details JavaScript's core components, client-side and server-side scripting, and various data types, operators, and methods for user interaction. Additionally, it explains how to embed JavaScript in HTML documents and includes examples of alert, confirm, and prompt boxes.

Uploaded by

computergsv
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)
2 views

JavaScript-JS

This document provides an overview of JavaScript, covering its basics, origins, uses, and differences from Java. It details JavaScript's core components, client-side and server-side scripting, and various data types, operators, and methods for user interaction. Additionally, it explains how to embed JavaScript in HTML documents and includes examples of alert, confirm, and prompt boxes.

Uploaded by

computergsv
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/ 38

lOMoARcPSD|43732916

UNIT-II: JAVASCRIPT
The Basic of Java script: Objects, Primitives, Operations and Expressions, Screen Output and
Keyboard Input, Control Statements, Object Creation and Modification, Arrays, Functions,
Constructors, Pattern Matching using Regular Expressions
DHTML: Positioning Moving and Changing Elements
ORIGINS:
JavaScript was originally developed at Netscape by Brendan Eich. Initially named Mocha but
soon after was renames LiveScript. In late 1995, LiveScript became a joint venture of Netscape and
Sun Micro Systems and its name changed again to JavaScript. A language standard for JavaScript
was developed by European Computer Manufacturers Association (ECMA) as ECMA – 262. This
standard is now in Version6. Since 2016 new versions are named by year (ECMAScript 2016 / 2017
/ 2018). The official name of this standard language is ECMA Script, but it becomes popular with the
name “JavaScript”.

JavaScript can be divided into three parts:

1. The Core
The core is the heart of the language includes its operators, expressions, statements and sub –
programs.
2. Client Side
Client – Side script is a collection of objects that supports the control of a browser and
interactions with users. For example, with JavaScript, an HTML document can respond to the
user inputs such as mouse clicks and keyboard events.
3. Server Side
Server – Side Script is a collection of objects that makes language useful on a web server. For
example, to communicate with database management system
USES OF JAVASCRIPT:

The original goal of JavaScript was to provide the programming capability at both server and
client ends of web connection.
Client Side Script can serve as an alternative to perform the tasks done at the server – side. It
reduces computational tasks on server side. But it cannot replace all server side computing which
include file operations, database access, networking, etc.
Interaction with the users through form elements such as buttons and menus can be conveniently
performed with the use of JavaScript.
JavaScript is event driven; it is meant that an HTML document with embedded JavaScript is
capable to respond to the user actions such as mouse clicks, button presses, keyboard strokes, etc.

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

DOM is the main capability of JavaScript that makes static HTML Documents as highly
dynamic, which allows accessing and modifying the style properties and content of the elements
of HTML document.
JavaScript can be used to create cookies.
JavaScript is used to validate the data on the web page before submitting it to the server.

DIFFERENCES BETWEEN JAVA & JAVASCRIPT

Java Java script


1. Java is a Programming language 1. Java script is a scripting language
2. Java is an object-oriented language 2. Java script is an object-based language
3. Objects in Java are Static. i.e., the number 3. In JavaScript the objects are dynamic. i.e.,
of data members and method are fixed at we can change the total data members and
compile time. method of an object during execution.
4. Java is strongly typed language, and type 4. Java script is loosely typed language. And
checking is done at compile time. type checking is done at run time.
5. Difficult to understand 5. Java script is comparatively easier to
understand

HTML – JAVASCRIPT DOCUMENTS


If an HTML document does not include embedded scripts, the browser reads the lines of the
document and renders its window according to the tags, attributes and the content it finds. When a
JavaScript script is encountered in the document then the browser uses it JavaScript interpreter to
“execute” the script.
There are two ways to embed the script in an HTML document, either implicitly or explicitly.
In explicit embedding, the JavaScript code physically resides in the HTML document. We can
embed the JavaScript code as follows:
<script type= “text/javascript”>
----------
----------
----------
</script>
In implicit embedding, the JavaScript code can be placed in a separate .js file, and linked to the
HTML document. This can be done as follows:
<script type= “text/javascript” src= “Mypage.js”>
</script>

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

Implicit embedding has the advantage of hiding the script from the browser user. When
scripts are embedded in HTML Document, they can appear in either head or body part of the HTML
document depending on the purpose. Scripts that produce the content only when as a response to the
user actions are placed in head section of the document. Scripts that are to be interpreted just once,
only when the interpreter finds are placed in the body section of the document.
PRIMITIVE DATA TYPES
Java script has five primitive types: Number, String, Boolean, Undefined and Null. Undefined and
Null are often called trivial types.
All numerical literals are primitive values of type Number. The Number type values are
represented internally in double – precision floating point form. Numerical Literals in a script
can be integers or floating point values.
A string literal is a sequence of characters delimited by either single quotes or double quotes.
String literals can also include escape characters such as \t, \n,…...
The only values of type Boolean are true and false. These values are usually computed as the
result of evaluating a relational or Boolean expression.
If a variable has been explicitly declared but not assigned a value. It has value undefined.
Null indicates no value. A variable is null if it has not been explicitly declared. If an attempt
is made to use a variable whose value is null, it causes a runtime error.
DECLARING VARIABLES
In JavaScript, variables are dynamic typed this means that the variable can be used for any
type. Variables are not typed. A variable can have the value of any primitive type or it can be a
reference to any object.
The type of the value of the variable in a program can be determined by the interpreter.
Interpreter converts the type of a value to whatever is needed for the context.
A variable can be declared either by assigning it a value, then the interpreter implicitly declares it or
declare it explicitly using the keyword var.
Examples:
var counter;
var index=0;
var pi=3.14159265;
var status=true;
var color= “greeen”;
A variable that has been declared but not assigned a value has the value undefined.

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

JAVASCRIPT RESERVED WORDS


JavaScript has 25 reserved words. Reserved words have some meaning and it is allowed to
use for that purpose only.
break delete function Return typeof
case Do if Switch var
catch Else in This void
continue finally instanceof Throw while
default For new Try with

SCREEN OUTPUT AND KEYBOARD INPUT


ALERT BOX:

Alert box is a very frequently useful to send or write cautionary messages to end user screen.
Alert box is created by alert method of window object as shown below.

Syntax: - window. alert (“message”);

When alert box is popup, the user has to click ok to continue browsing or to perform any
further operations.

Example:
<html>
<head>
<title> alert box </title>
<script language="JavaScript">
function add( )
{
a=20;
b=40;
c=a+b;
window.alert("This is for addition of 2 no's");
} document.write("Result is: "+c);
</script>
</head>
<body onload="add( )">
</body>
</html>
Output:

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

Result is 60

CONFIRM POPUP BOX:

This is useful to verify or accept something from user. It is created by confirm method of
window object as shown below.

Syntax:- window.confirm (“message?”);

When the confirm box pop„s up, user must click either ok or cancel buttons to proceed. If
user clicks ok button it returns the boolean value true. If user clicks cancel button, it returns the
boolean value false.

Example: -
<HTML>
<HEAD>
<TITLE> Confirm </TITLE>
<script>
function sub( )
{
a=50;
b=45;
c=a-b;
x=window.confirm("Do you want to see subtraction of numbers")
;if(x==true)
{
document.write("result is :"+c);
}
else
{
document.write("you clicked cancel button");
}
}
</script>
</HEAD>
<BODY onload="sub( )">
To see the o/p in pop up box:
</BODY>
5

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

</HTML>
Output:

To see the o/p in pop up box:

result is :5

PROMPT POPUP BOX:-


It is useful to accept data from keyboard at runtime. Prompt box is created by prompt method
of window object.
Syntax: window.prompt (“message”, “default text”);

When prompt dialog box arises user will have to click either ok button or cancel button after
entering input data to proceed. If user click ok button it will return input value. If user click cancel
button the value ―null will be returned.

Example:

<HTML>
<HEAD>
<TITLE> Prompt </TITLE>
<script>
function fact( )
{
var b=window.prompt("enter +ve integer :","enter here");
var c=parseInt(b);
a=1;
for(i=c;i>=1;i--)
{
a=a*i;
}
window.alert("factorial value :"+a);
}
</script>
</HEAD>
<BODY onload="fact( )">
</BODY>
</HTML>

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

Output:

Write ( ) Method:

The write( ) method in HTML is used to write some content or JavaScript code in a Document.

Syntax: document. write (exp1, exp2, exp3, ...);

Here, exp1, exp2, exp3 ….. are all optional arguments, these are arguments are appended to the
document in order of occurrence

The writeln() method is identical to the document.write() method, with the addition of writing
a newline character after each statement.
Example:
<!DOCTYPE html>
<html>
<body>
<p>Note that write() does NOT add a new line after each statement:</p>
<script>
document.write("Hello World!");
document.write("Have a nice
day!");
</script>
<p>Note that writeln() add a new line after each statement:</p>
<script>
document.writeln("Hello World!");
document.writeln("Have a nice
day!");
</script>
</body>
</html
Output:

Note that write() does NOT add a new line after each statement:

Hello World!Have a nice day!

Note that writeln() add a new line after each statement:


7

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

Hello World!
Have a nice day!

OPERATORS IN JAVASCRIPT
In JavaScript, an operator is a special symbol used to perform operations on operands (values
and variables).

For example, 2 + 3; // 5
Here + is an operator that performs addition, and 2 and 3 are operands.
JavaScript supports the following types of operators.

Arithmetic Operators
Comparison (or Relational) Operators
Logical Operators
Assignment Operators
Conditional (or ternary) Operators

ARITHMETIC OPERATORS
JavaScript supports the following arithmetic operators −
Assume variable A holds 10 and variable B holds 20, then −

S. No. Operator & Description


1
+ (Addition)
Adds two operands
Ex: A + B will give 30
2
- (Subtraction)
Subtracts the second operand from the first
Ex: A - B will give -10
3
* (Multiplication)
Multiply both operands
Ex: A * B will give 200
4
/ (Division)
Divide the numerator by the denominator
Ex: B / A will give 2

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

5
% (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0
6
++ (Increment)
Increases an integer value by one
Ex: A++ will give 11
7
-- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9

COMPARISON OPERATORS
Comparison Operators also called relational operators, used to write conditions in the statements
like if, if – else, switch, loop statements. Expressions that include these set of operators
evaluated to true or false.
JavaScript supports the following comparison operators −
Assume variable A holds 10 and variable B holds 20, then −
Sr.No. Operator & Description
1 = = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition becomes
true.
Ex: (A == B) is not true.
2 != (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal, then the
condition becomes true.
Ex: (A != B) is true.
3 > (Greater than)
Checks if the value of the left operand is greater than the value of the right operand, if
yes, then the condition becomes true.
Ex: (A > B) is not true.
4 < (Less than)
Checks if the value of the left operand is less than the value of the right operand, if yes,
then the condition becomes true.
Ex: (A < B) is true.
5 >= (Greater than or Equal to)
Checks if the value of the left operand is greater than or equal to the value of the right
operand, if yes, then the condition becomes true.
Ex: (A >= B) is not true.
6 <= (Less than or Equal to)
Checks if the value of the left operand is less than or equal to the value of the right
operand, if yes, then the condition becomes true. Ex: (A <= B) is true.

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

7 = = = (is strictly equal to)


This operator checks for the equality of two operands it terms of its value as well as its
type. If two operands have same type and have equal value then it returns true otherwise
false
8 ! = = (is strictly not equal to)
This operator returns true if the both operands do not have equal value and of different
data types.

LOGICAL OPERATORS
Logical Operators are used to combine two or more conditions into single condition. For these
operators, and the logical expressions are evaluated to either true or false.
JavaScript supports the following logical operators −
S.No. Operator & Description
1 && (Logical AND)
If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.
2 || (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
3 ! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical NOT
operator will make it false.
Ex: ! (A && B) is false.

ASSIGNMENT OPERATORS
Assignment operators are used to assign a literal value or value of an expression to variable.
JavaScript supports the following assignment operators −
Sr.No. Operator & Description
1 = (Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C
2 += (Add and Assignment)
It adds the right operand to the left operand and assigns the result to the left operand.
Ex: C += A is equivalent to C = C + A
3 −= (Subtract and Assignment)
It subtracts the right operand from the left operand and assigns the result to the left
operand.
Ex: C -= A is equivalent to C = C – A
4 *= (Multiply and Assignment)
It multiplies the right operand with the left operand and assigns the result to the left
operand.
Ex: C *= A is equivalent to C = C * A

10

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

5 /= (Divide and Assignment)


It divides the left operand with the right operand and assigns the result to the left
operand.
Ex: C /= A is equivalent to C = C / A
6 %= (Modules and Assignment)
It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A

CONDITIONAL OPERATOR (? :):-


The conditional operator first evaluates an expression for a true or false value and then
executes one of the two given statements depending upon the result of the evaluation of condition.
Usage:
Conditional - Expression? Expression 1: Expression 2;
If the condition is evaluated to true then the expression1 is executed, otherwise expression 2
is executed.
TYPEOF OPERATOR
The typeof operator is a unary operator used to check the type of variable given to it.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number,
string, or boolean.
Here is a list of the return values for the typeof Operator.

Type String Returned by typeof


Number "number"
String "string"
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"

STRING CONCATENATION OPERATOR


Joining multiple strings together is known as concatenation. To join two or more strings together into
a single string, the concatenation operator (+) is used. It concatenates two or more string values
together and returns another string which is the union of the two operand strings.

Example 1:
var txt1 =
"John"; var txt2
= "Doe";
var txt3 = txt1 + " " + txt2; // now txt3 contains “John Doe”
11

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

Example 2:

var txt1 = "What a very ";


txt1 += "nice day"; // now txt1 contains “What a very nice day”

If a number and a string is added then the result will be the string

Example:

var x = 5 + 5; // Now x has 10


var y = "5" + 5; // Now the variable y has 55
var z = "Hello" + 5; // Now the variable z has Hello5

TYPE CONVERSIONS
There are two types of type conversions (or) typecasting,

Implicit Conversion (casting) done by JavaScript Interpreter


Explicit Conversion (casting) is done by the developer

IMPLICIT TYPE CONVERSION

Converting one type of data value to another type is called typecasting. If required JavaScript
engine automatically converts one type of value into another type. It will try to convert it to the right
type.
Example:
1. “Survey_number”+10
The result of above operation will get a string
“Survey_number 10”
2. 5*”12”
Second operand which is a String will automatically converted to number.
The result is 60.
3. 5*”Hello”
Second operand which is a String cannot be converted to number.
The result is NaN –Not a number.
When implicit type conversion is made, the result is always not as expected
Examples:
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

12

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

EXPLICIT TYPE CONVERSION


In explicit type conversion, the programmer forcefully converts the one data type to another
data type using the following functions:
Number () – it converts the given number into the binary, octal, and hexadecimal
Boolean () – converts any type of given value into true or false (or) 0 and 1
ParseInt () –converts the numerical string to an integer value
ParseFloat () – converts the numerical string to a float value
String () – it converts any given type of value into string type
toString () – it converts any given type of value into string type

Number ( ):
Number() function in used to convert a value to a Number. It can convert any numerical
text and boolean value to a Number. In case of strings of non-numerics, it will convert it to a NaN
(Not a Number)

Example:
var s = "144";
var n = Number(s); // now n contain 144(Number)

var s = true;
var n = Number(s); // now n contain 1(Number)

Boolean ( ):
It converts any type of value to true or false

Example:
var s = 1;
var n = Boolean(s); // now n contain true(Boolean)

var s = “0”;
var n = Boolean(s); // now n contain false(Boolean)

var s = “20”;
var n = Boolean(s); // now n contain true(Boolean)

var s = “twenty”;
var n = Boolean(s); // now n contain true(Boolean)

var s = “”; //empty string


var n = Boolean(s); // now n contain false(Boolean)

parseInt ( ):
This function is used to convert a numerical string into integer, if string contains non –
numerical values then it returns NaN (Not a Number).

13

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

Example:
var s = “20”;
var n = parseInt(s); // now n contain 20 (integer)

var s = “twenty”;
var n = parseInt(s); // now n contain NaN (Not a Number)

var s = “19twenty”;
var n = parseInt(s); // now n contain 19 (integer)

Here, this function parses up to numerical characters when it finds non – numerical
character then it stops parsing.

parseFloat ( )
The parseFloat() function is used to convert the string into a floating-point number. If
the string does not contain a numeral value or if the first character of the string is not a Number
then it returns NaN i.e, not a number. It actually returns a floating-point number parsed up to that
point where it encounters a character that is not a Number.

Example:
var s = “20.56”;
var n = parseInt(s); // now n contain 20.56 (float value)

toString( )

The toString() method in Javascript is used with a number and converts the number to a
string. It is used to return a string representing the specified Number object.

Syntax:
num.toString(base) // base specifies the number system

Example:
var num=12;
document.write("Output : " + num.toString(2));
Here, it displays 1100 in binary number system

var num=12;
document.write("Output : " + num.toString(10));
Here it displays 12 in decimal number systems

var num=12;
document.write("Output : " + num.toString(8));

Here, it displays 14 in octal number systems

14

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

CONTROL STATEMENTS
Control Structures are used to control sequential flow of program execution in desired
manner to solve the problem.

SELECTION STATEMENTS

Selection Statements are used to select one alternative among the two or more available set of
statements. These conditional statements allow you to take different actions depending upon
different conditions. There are three conditional statements:

if statement, which is used when you want the script to execute if a condition is true
if...else statement, which is used when you want to execute one set of code if a condition is true
and another if it is false
switch statements, which are used when you want to select one block of code from many
depending on a situation

IF STATEMENT:

This statement is used to decide whether a block of code is to be executed or not. If the
condition is true then the code in the curly braces is executed. Here is the syntax of IF statement:

if (condition)
{
Statements
}
IF . . . ELSE STATEMENT
When you have two possible situations and you want to react differently for each, you can
use if...else statement. This means: “If the conditions specified are met, run the first block of code;
otherwise run the second block”. The syntax is as follows:

if (condition)
{
Statements
}
else
{
Statements
}

15

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

Example:
<html>
<head>
<title>if/else</title>
</head>
<body>
<script type=”text/javascript”>
var a,b,c;
a=10;b=20;c=30;
if(a>b)
{
if(a>c)
document.write(“a is largest number”+a);
else
} document.write(“c is largest number”+c);
else
{
if(b>c)
document.write(“b is largest number”+b);
else
} document.write(“c is largest number”+c);
</script>
</body>
</html>
SWITCH STATEMENT

A switch statement allows you to deal with several possible results of a condition. You have a
single expression. The value of this expression is then compared with the values for each case in the
structure. If there is a match, the block of code will execute.

Syntax:
switch (expression)
{
case value1: statement(s)
break;
case value2: statement(s) You use the break to prevent code from running into
break; the next case automatically.
………………….
………………….
default: statement(s)
break;
}

16

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

Ex:

<html>
<head>
<title>switch</title>
</head>
<body>
<script type=”text/javascript”>
var d=new Date();
ch=d.getMonth();
switch(ch)
{
case 0:document.write(“January”);
break;
case 1:document.write(“february”);
break;
case 2:document.write(“march”);
break;
case 3:document.write(“april”);
break;
case 4:document.write(“may”);
break;
case 5:document.write(“june”);
break;
case 6:document.write(“July”);
break;
case 7:document.write(“august”);
break;
case 8:document.write(“september”);
break;
case 9:document.write(“october”);
break;
case 10:document.write(“november”);
break;
case 11:document.write(“december”);
break;
default: document.write(“Invalid choice”);
}
</script>
</body>
</html>

17

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

LOOP CONTROL STATEMENTS


Loop statements are used to execute the same block of code repeatedly to required number of times
based on the truth value of a condition. JavaScript supports three looping statements

A while loop that runs the same block of code while or until a condition is true.
A do while loop that runs once before the condition is checked. If the condition is true, it will
continue to run until the condition is false. The difference between while and do-while loop is
that do while runs once whether the condition is true or false.
A for loop that runs the same block of code a specified number of times

WHILE STATEMENT

In a while loop, a code block is executed repeatedly until the condition becomes false. The syntax is
as follows:

while (condition)
{
Block of statements
}
Ex:
<html>
<head>
<title>while</title>
</head>
<body>
<script type=”text/javascript”>
var i=1;
while(i<=10)
{
document.write(“Number”+i+”It‟s square”+(i*i)+”<br/>”)
i++;
}
</script>
</body>
</html>
DO . . . WHILE STATEMENT

A do ... while loop executes a block of code once and then checks a condition. As long as the
condition is true, it continues to loop. So, without evaluating the condition, the statements in the loop
runs at least once. Here is the syntax:

do
{
Statements
} while (condition);

18

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

Ex:
<html>
<head>
<title>do - while</title>
</head>
<body>
<script type= “text/javascript”>
var i=1;
do
{
document.write(“Number”+i+”It‟s square”+(i*i)+”<br/>”)
i++;
} while(i<=10);
</script>
</body>
</html>

FOR STATEMENT
The FOR LOOP statement executes a block of code a specified number of times. You use it
when you want to specify how many number of times body of the loop is executed.

Here is the syntax:

for (initialization; test condition; increment/decrement)


{
Statements
}
Ex:
<html>
<head>
<title>FOR LOOP STATEMENT </title>
</head>
<body>
<script type=”text/javascript”>
var i;
for(i=1;i<=10;i++)
{
document.write(“Number”+i+”It‟s square”+(i*i)+”<br/>”)
}
</script>
</body>
</html>

19

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

BREAK STATEMENT

In general, a loop statement is terminated when the condition becomes false. The break
statement is used to break the loop forcefully even though the loop condition is true. And the break
statement is allowed to use with the conditional statement only.

Ex:

<html>
<head>
<title>break</title>
</head>
<body>
<script type=”text/javascript”>
var i;
for(i=10;i>=1;i--)
{
if(i==5)
break;
}
document.write(“My lucky Number is:”+i”)
</script>
</body>
</html>
CONTINUE STATEMENT
The continue statement is used in a loop to stop the execution of loop statements for the
current iteration and continue with the remaining iterations. And the continue statement is allowed
to use with the conditional statement only

<html>
<head>
<title>continue</title>
</head>
<body>
<script type=”text/javascript”>
var i;
for(i=10;i>=1;i--)
{
if(i==5)
{
x=i;
continue;
}
document.write(i+”<br/>”);
}

20

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

document.write(“My missed Number is:”+x”)


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

A function is a piece of code that performs a specific task. The function will be executed by
an event or by a call to that function. We can call a function from anywhere within the page (or even
from other pages if the function is embedded in an external .js file). JavaScript has a lot of built – in
functions.
Defining functions:
JavaScript function definition consists of the function keyword, followed by the name of the
function. A list of arguments to the function are enclosed in parentheses and separated by commas.
The statements within the function are enclosed in curly braces { }.
Syntax:

function function_name(var1,var2,...,varX)

Parameter Passing:

The parameters values that appear in a call to a function are called actual parameters. The
parameters those receives the actual parameters in the function definition when it calls are called
formal parameters.
Not every function accepts parameters. When a function receives a value as a parameter, that
value is given a name and can be accessed using that name in the function. The names of
parameters are taken from the function definition and are applied in the order in which parameters
are passed in.
The number of actual parameters in a function call is not checked against the number of
formal parameters. In function if actual parameters are excess in number then they are ignored, if the
lesser in number, then the excess formal parameters are undefined.
Primitive data types are passed by value in JavaScript. This means that a copy is made of a
variable when it is passed to a function, so any modifications made to that parameter does not affect
the original value of the variable passed.
Unlike primitive data types, composite types such as arrays and objects are passed by
reference rather than value. If references are passed then only changes made in the function affects
the actual parameters.

21

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

JavaScript uses pass – by – value parameter passing method. However, if a reference to an


object is passed to a function and the function made any changes to the formal parameter then the
change has no effect on the actual parameter.
A value can also be returned from the function using the keyword return. This return
statement can be written at the end of the function usually as the control flow goes back to the calling
statement.
Example:
<html>
<head>
<title>Defining a function</title>
<script type=”text/javascript”>
function name()
{
str= “vignan”;
return str;
}
</script>
</head>
<body>
<script type=”text/javascript”>
document.write(“Department of IT”);
var x=name();
document.writeln(“Welcome to” + x);
</script>
</body>
</html>

Examining the function call:


In JavaScript parameters are passed as arrays. Every function has two properties that can be
used to find information about the parameters:
arguments - This is an array of parameters that have been passed
arguments.length - This is the number of parameters that have been passed into the function
Example:

<html>
<head>
<script type="text/javascript">
function params(a,b)
{
document. writeln("<br/>No of parameters passed:"+arguments.length);
document.writeln("<br/>Parameter Values are:")
for(var i=0;i<arguments.length;i++)

22

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

}
return;
}

document.writeln("<br/>Parameter"+(i+1)+" "+arguments[i]);
</script>
</head>
<body>
<script type="text/javascript">
params("Ajay", "Arun");
params("Ajay","Arjun","Anand");
</script>
</body>
</html>
Output:
No of parameters
passed:2 Parameter
Values are:
Parameter1
Ajay
Parameter2
Arun
No of parameters
passed:3 Parameter
Values are:
Parameter1 Ajay
Parameter2 Arjun
Parameter3
Anand

SCOPE OF VARIABLES
The scope of a variable is the range of statements over which it is visible. When the
JavaScript is embedded in an HTML document, the scope of the variable is the range of lines of the
document over which the variable is visible.
Variables that are declared explicitly using the keyword var, inside a function have LOCAL
SCOPE and they can be allowed to access in that function only.
Variables that are declared explicitly using the keyword var, outside to all functions have
GLOBAL SCOPE and they can be allowed to access anywhere.
Variables that are not declared explicitly, and implicitly declared by JavaScript interpreter,
without using the keyword var have GLOBAL SCOPE and they are accessed anywhere in
the HTML document. Even though, if such an implicit declaration has made inside a
function, its scope is GLOBAL.
23

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

If a variable that is defined both as a Local Variable and Global Variable then the local
variable has more precedence, then the global variable is hidden.

JAVASCRIPT OBJECTS
In JavaScript, Objects are collection of properties, which may be either a data property or a
function or a method.
 Data properties are appear in two categories: primitive values or references to other objects.
 Sub programs that are called through objects are called methods.
 Sub programs that are not called through objects are called functions.

All objects in a JavaScript are indirectly accessed through variables. The properties of an object
are referenced by attaching the name of the property to the variable that references the object. For
example, if car is the variable that refers an object that has the property engine, this engine
property can be accessed as car.engine.
The root object in JavaScript is Object. It is ancestor to all the objects.
A JavaScript Object can appear as a list of property – value pairs. The properties are names and
values are data values.
Properties of objects can be added or deleted at any time during execution. So they are Dynamic.

OBJECT CREATION AND MODIFICATION

The web designer can create an object and can set its properties as per his requirements. The
object can be created using new expression. Initially the object with no properties can be set using
following statements.

obj=new Object();

Then by using dot operator we can set the properties for that object. The object can then be
modified by assigning values to that object.

Example:
<html>
<head>
<title>Object creation</title>
</head>
<body>
<script type=”text/javascript”> var
student;
student=new Object(); student.id=10;
student.name=”Vignan”;
24

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

document.write(“The ID is:”+student.id);
document.write(“The Name is:”+student.name);
</script>
</body>
</html>
JAVASCRIPT CONSTRUCTORS
 Objects in Java Script are created using the constructors too.
 Constructors are like regular functions, but we use them with the new keyword.

There are two types of constructors:

1. Built-in constructors such as Array and Object, which are available automatically in the
execution environment at runtime
2. Custom constructors, which define properties and methods for your own type of object.

A constructor is useful when you want to create multiple similar objects with the same properties
and methods. It’s a convention to capitalize the starting letter in the name of constructor to
distinguish them from regular functions.

Consider the following code:

function Book()
{
// unfinished code
}
var myBook = new Book();

The above line of the code creates an instance of Book and assigns it to a variable.

Although the Book constructor doesn't do anything, myBook is still an instance of it. And it is
possible to add the properties to the instance myBook dynamically. This can be illustrated in the
following example:

<html>
<body><script type= “text/javascript”>
function Book()
{
this. title= “Programming WWW”;
this. price = 500.00;
this. author= “Tim Berners Lee”;
}
var myBook = new Book(); Document.writeln(“Book
Title:”+myBook.title); Document.writeln(“Book
Author”+myBook.author);Document.writeln(“Book
Price:”+myBook.price);
25

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

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

Determining the type of an instance:

To find out whether an object is an instance of another one, we use the instanceof operator:
myBook instanceof Book // true
myBook instanceof String // false

Note that if the right side of the instanceof operator isn‟t a function, it will throw an error:
myBook instanceof {};
// TypeError: invalid 'instanceof' operand ({})

Another way to find the type of an instance is to use the constructor property.
Consider the following code fragment:
myBook.constructor === Book; // true

The constructor property of myBook points to Book, so the strict equality operator returns
true.

STRING OBJECT
String is a set of characters enclose in a pair of single quotes or double quotes. In JavaScript

26

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

using string object, many useful string related functionalities can be done. Some commonly used
methods of string object are concatenating two strings, converting the string to uppercase or
lowercase, finding the substring of a given string and so on.
A String object can be declared as follows:
var str = new String(“Vignan LARA”);

PROPERTY:
Length
This property of string returns the length of the string
Example:
var str = new String(“Vignan LARA”);
str.length //gives 5

METHODS:
1. charAt(index)
This method returns the character specified by index
Example:
var str = new String(“Vignans LARA”);
str.charAt(2); // this gives the character at the index position 2 i.e. g
2. indexOf(substring [, offset])
This method returns the index of substring if found in the main string. If the substring is not found
then it returns -1. By default the indexOf( ) function starts searching the substring from index 0,
however, an optional offset may be specified, so that the search starts from that position.

Example:
var str = new String(“Vignan LARA”);
str.indexOf(“LARA”); // This gives the index position 7 as it founds the “LARA” there.
3. lastIndexOf(substring [,offset])
This method returns the index of substring if found in the main string (i.e. last occurrence). If the
substring is not found then it returns -1. By default the lastIndexOf() function starts from the last
index i.e. from backwards, however, an optional offset may be specified, so that the search starts
from that position in backwards.

Example:
var str = new String(“Vignan LARA”);
str.lastIndexOf(“LARA”);

27

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

4. str1.concat(str2 [,str3 ..strN])


This method is used to concatenate strings together.
For example, s1.concat(s2) returns the concatenated string of s1 and s2. The original stringsdon‟t
get altered by this operation.
var s1=“Hello”; var
s2=“Vignan”;
var s3 = s1.concat(s2);
Now s3 contains the string Hello Vignan
5. substring(start [,end] )
This method returns the substring specified by start and end indices (upto end index, but not the
character at end index). If the end index is not specified, then this method returns substring from
start index to the end of the string.
Example:
var str = new String(“Vignan LARA”);
str.substring(7); // This gives the string from the index position 7 to the end of the string.
str.substring(0, 7); // This gives the string from the index position0 to 6
6. substr(index [,length])
This method returns substring of specified number of characters (length), starting fromindex. If the
length is not specified it returns the entire substring starting from index.

Example:
“Vignan LARA”.substr(7,4);
It returns the sub string of 4 characters length from index position 7 i.e. LARA
7. toLowerCase( )
This method returns the given string converted into lower case. The original string is not altered by
this operation.
Example:
var str = new String(“Vignan LARA”);
str.toLowerCase();
8. toUpperCase( )
This method returns the given string converted into upper case. The original string is notaltered by
this operation.
Example:
var s="Vignan LARA";
s.toUpperCase();

28

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

9. split(separator [,limit] )
Splits the string based on the separator specified and returns that array of substrings. If the
limit is specified only those number of substrings will be returned
Example1:
var s="VLITS#LARA#GNT#AP";
var t =s.split("#");
Now, the variable t contains an array of sub strings – VLITS, LARA, GNT, AP.
MATH OBJECT
The Math Object provides a collection of properties of Number Objects and the methods that
operate on Number Objects. This Math object has methods for the trigonometric functions such as
sin, cos as well as other commonly used operations such as sqrt (), round (), floor (), ceil (), abs (),
log (), etc.

The following example rounds PI to the nearest whole number (integer) and writes it to the screen.

var numPI = Math.PI;


numPI = Math.round(numPI);
document.write (numPI);

Example:
<html>
<head>
<title>Math object</title>
</head>
<body>
<script type=”text/javascript”>
var number=100;
document.write(“Square root of number is:”+Math.sqrt(num));
</script>
</body>
</html>
For performing the mathematical computations there are some useful methods available from math
object.

a. sqrt(num) – returns the square root of given number where num > 0
b. abs(num) – returns the absolute value of num i.e it ignores the sign of the number
c. ceil(num) – returns the integer which is equal to the smallest of the integers those are
greaterthan num.
d. floor(num) – returns the integer which is equal to the largest of the integers those are
smaller than num.
e. pow(a,b) – returns the a to the power of b value
f. min(a,b) – returns the minimum of a and b.
g. max(a,b) – returns the maximum of a and b.
h. sin(num) – returns the sine value of num.
29

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

i. cos(num) – returns the cosine value of num.


j. tan(num) – returns the tan value of the given num.
k. exp(num) – returns the e to the power of num.
DATE OBJECT
The Date object is used when the information about the current date and time is useful in the
program. The Date object contains a collection of methods that are used to perform the manipulation
operations on date and time values.
A Date object is created as follows:
var today = new Date();
Here, today is the object of type Date that contains the current system date and time.
This Date and Time value is in the form of computer‟s local time (system‟s time) or it can be
in the form of UTC(Universal Coordinated Time), formerly known as GMT (Greenwich Mean
Time).
It is also possible to create a date object that set to a specific date or time, in which case you
need to pass it one of four parameters:
l. One can pass milliseconds – this value should be the number of milliseconds from
01/01/1970.
var bday = new Date(milliseconds);
2. One can pass the date in the form of string
var bday = new Date(string);
3. One can pass year, month, and day.
var bday = new Date(year, month, day);
4. One can pass year, month, day, hour, minutes and seconds
var bday = new Date(year, month, day, hour, minutes, seconds);

The following table is the list of some of the methods of Date Object:
5. getDate() – returns the day of the month.
6. getMonth() – returns the month of the year, ranges from 0 to 11
7. getDay() – returns the day of the week ranges from 0 to 6
8. getFullYear – returns the year
9. getTime () – returns the number of milliseconds from Jan 1, 1970
10. getHours() – returns the number of hours range from 0 to 23
11. getMinutes – returns the number of minutes range from 0 to 59
12. getSeconds – returns the number of seconds range from 0 to 59
13. getMilliseconds – returns the number of milliseconds range from 0 to 999.
30

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

Example:
<html>
<head>
<title>Date object</title>
</head>
<body>
<script type=”text/javascript”>
var mydate=new Date();
document.write(“The Date is:”+mydate.toString()+”<br/>”);
document.write(“Today‟s Date is:”+mydate.getDate()+”<br/>”);
document.write(“Current year is:”+mydate.getFullYear()+”<br/>”);
document.write(“Minutes is:”+mydate.getMinutes()+”<br/>”);
document.write(“Seconds is:”+mydate.getSeconds()+”<br/>”);
</script>
</body>
</html>
Output:
The Date is: Fri May 07 2021 19:22:10 GMT+0530
Today Date is: 7
Current year is:
2021 Minutes is: 22
Seconds is: 10
ARRAYS
Array is a collection of similar type of elements which can be referred by a common name.
Any element in an array is referred by an array name. The particular position of an element in an
array is called “Index” or “Subscript”.
In java script the array can be created using array object.
Create an Array:
An array can be created in following ways:
1. var arrName= [“a”,”b”.”c”];
2. var arrName= new Array(3); // 3 is the size
arrName[0]= “a”;;
arrName[1]= “b”;
arrName[2]= “c”;
31

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

3. var arrName=new Array(“a”, “b”, “c”);


Here “a”, “b”, “c” are elements of the array
<html>
<head>
<title>Defining a function</title>
</head>
<body>
<script type=”text/javascript”>
var a=new Array(5);
for(i=0;i<=5;i++)
{
a[i]=i; document.write(a[i]+”<br/>”);
}
</script>
</body>
</html>
4. One property that is frequently used to determine number of elements in an array is length.
Example:
var list = [11,22,33,44,55];
document.writeln(“Length of the list is”+list.length); // displays the length 5
Array Methods:

Here is a list of the methods of the Array object along with their description.
S.
Method & Description
No.
concat()
Returns a new array comprised of this array joined with other array(s) and/or value(s).
1 var arr1 = ["Cecilie", "Lone"];
var arr2 = ["Emil", "Tobias", "Linus"];
var arr3 = ["Robin", "Morgan"];
var myChildren = arr1.concat(arr2, arr3); // Concatenates arr1 with arr2 and arr3
indexOf()
Returns the first (least) index of an element within the array equal to the specified value, or -1 if
2 none is found.
var fruits = ["Banana", "Orange", "Apple", "Mango", "Orange"];
document.writeln(fruits.indexOf("Orange")); // it gives 1

32

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

lastIndexOf()
Returns the last (greatest) index of an element within the array equal to the specified value, or -1
3 if none is found.
var fruits = ["Banana", "Orange", "Apple", "Mango", "Orange"];
document.writeln(fruits.lastIndexOf("Orange")); // it gives 4

pop()
Removes the last element from an array and returns that element.
4
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop(); // Removes the last element ("Mango") from fruits
push()
Adds one or more elements to the end of an array and returns the new length of the array.
5
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi"); // Adds a new element ("Kiwi") to fruits
reverse()
Reverses the order of the elements of an array -- the first becomes the last, and the last becomes
the first.
6

var fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits.reverse(); // it gives “Mango”, “Apple”, “Orange”, “Banana”
shift()
Removes the first element from an array and returns that element.
7
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift(); // Removes the first element "Banana" from fruits

unshift()
Adds one or more elements to the front of an array and returns the new length of the array.
8
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon"); // Adds a new element "Lemon" to fruits
slice()
Extracts a section of an array and returns a new array.
9
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.slice(2); // it extracts a new array starting from index 2 i.e. Apple

sort()
Sorts the elements of an array
10
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort() // it gives “Apple”, “Banana”, “Mango” , “Orange”

33

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

toString()
Returns a string with array elements separated by Commas
11
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.writeln(fruits.toString()); // it gives “Banana, Orange, Apple, Mango”

Passing An Array to Function:


We can pass an entire array as a parameter to the function. When an array is passed to the function
the array name is simply passed.
Example:
<html>
<head> <title>passing array to a function</title>
<script type=”text/javascript”>
function display(a)
{
document.write(“The array elements are:”);
i=0;
while(i <a.length)
{
document.write(a[i]+”<br/>”);
i++;
}
}
</script>
</head>
<body>
<script type=”text/javascript”> var
arr=[11, 22, 33, 44, 55];
display(arr);
</script>
</body>
</html>
PATTERN MATCHING USING REGULAR EXPRESSIONS
A regular expression is a sequence of characters that forms a search pattern. When you
search for data in a text, you can use this search pattern to describe what you are searching for.

34

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

A regular expression can be a single character, or a more complicated pattern. Regular


expressions can be used to perform all types of text search and text replace operations.
EXAMPLE:
Static Creation of Regular Expression
var patt = /w3schools/i;
/w3schools/i is a regular expression.
w3schools is a pattern (to be used in a search).
i is a modifier (modifies the search to be case-insensitive).
var str = “ Visit W3Schools”;
str.match (pattern);
Dynamic Creation of Regular Expression:
var pattern = new RegExp (“/w3schools/i”); var str
= “ Visit W3Schools”;
pattern.exec (str);

JavaScript has the below given Regular Expression Grammar:

Token Description

^ Match at the start of the input string

$ Match at the end of the input string

* Match 0 or more times

+ Match 1 or more times

? Match 0 or 1 time

a/b Match „a‟ or „b‟

{n} Match the string „n‟ times

\d Match a digit

\o Match anything except for digits

\w Match any alpha numeric character or the underscore

\W Match anything except alpha numeric characters or underscore

\s Match a white space character

35

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

\S Match anything except for white space characters

Create a set of characters, one of which must match, if the operation is to be successful. If
[---] we need to specify a range of characters, then separate the first & last with Hyphen (-)
Ex: [0-9] & [D-G].
Creates a set of characters which must not match.
[^---] If any character in the set matches then operation has failed.
Ex: [^d-q]

Regular Expressions using String Methods:


In JavaScript, regular expressions are often used with the string methods:
search() and replace().
5. The search() method uses an expression to search for a match, and returns the position of the
match.
6. The replace() method returns a modified string where the pattern is replaced.`

RegExp class functions


1. exec (string)
It executes a search for the matching pattern in its parameter string. It returns an array holding the
results of the operation. If the search fails then it returns the null value.
2. test (string)
Search for a match in its parameter string. Returns true if a match is found otherwise it
returns false

Using String search() With a Regular Expression


Use a regular expression to do a case-insensitive search for "w3schools" in a string:
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p>Search a string for "w3Schools", and display the position of the match:</p>
<script>
var str = "Visit W3Schools!";
var n = str.search(/w3Schools/i);
document.writeln(n);
</script>
</body>
</html>

36

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

Outcome:

Use String replace() With a Regular Expression


Use a case insensitive regular expression to replace Microsoft with W3Schools in a string:
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p>Replace "microsoft" with "W3Schools" 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/i,"W3Schools");
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
Outcome:

On clicking the Try it button, Web page is displayed as follows:


37

Downloaded by GSV Computer ([email protected])


lOMoARcPSD|43732916

38

Downloaded by GSV Computer ([email protected])

You might also like