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

Chapters

Regular expressions are patterns used to match character combinations in strings. They are used with JavaScript's regular expression object and string methods to perform searches and replacements. This chapter describes the syntax and components of regular expressions in JavaScript, including quantifiers, character sets, metacharacters, and flags that specify matching behavior.

Uploaded by

RUTVIJ TEMKAR
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views

Chapters

Regular expressions are patterns used to match character combinations in strings. They are used with JavaScript's regular expression object and string methods to perform searches and replacements. This chapter describes the syntax and components of regular expressions in JavaScript, including quantifiers, character sets, metacharacters, and flags that specify matching behavior.

Uploaded by

RUTVIJ TEMKAR
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 227

Regular expressions are patterns used to match character combinations in strings.

In JavaScript,
regular expressions are also objects. These patterns are used with the exec and test methods
of RegExp, and with the match, matchAll, replace, search, and split methods of String. This
chapter describes JavaScript regular expressions.

Regular expressions are used to perform pattern-matching and "search-and-


replace" functions on text.

Syntax
/pattern/modifiers;

RegularExp.html

Brackets
Brackets are used to find a range of characters:

Expression Description

[abc] Find any character between the brackets

[^abc] Find any character NOT between the brackets

[0-9] Find any character between the brackets (any digit)

[^0-9] Find any character NOT between the brackets (any non-digit)
(x|y) Find any of the alternatives specified

Metacharacters
Metacharacters are characters with a special meaning:

Metacharacter Description

. Find a single character, except newline or line terminator

\w Find a word character

\W Find a non-word character

\d Find a digit

\D Find a non-digit character

\s Find a whitespace character

\S Find a non-whitespace character


\b Find a match at the beginning/end of a word, beginning like this:
\bHI, end like this: HI\b

\B Find a match, but not at the beginning/end of a word

\0 Find a NUL character

\n Find a new line character

\f Find a form feed character

\r Find a carriage return character

\t Find a tab character

\v Find a vertical tab character

\xxx Find the character specified by an octal number xxx

\xdd Find the character specified by a hexadecimal number dd


\udddd Find the Unicode character specified by a hexadecimal number
dddd

Quantifiers
The frequency or position of bracketed character sequences and single characters can
be denoted by a special character. Each special character has a specific connotation.
The +, *, ?, and $ flags all follow a character sequence.

Sr.No. Expression & Description

1
p+
It matches any string containing one or more p's.

2
p*
It matches any string containing zero or more p's.

3
p?
It matches any string containing at most one p.

4
p{N}
It matches any string containing a sequence of N p's

5
p{2,3}
It matches any string containing a sequence of two or three p's.

6
p{2, }
It matches any string containing a sequence of at least two p's.

7
p$
It matches any string with p at the end of it.
8
^p
It matches any string with p at the beginning of it.

Comparison chart:

BASIS FOR
STATIC BINDING DYNAMIC BINDING
COMPARISON

Event Occurrence Events occur at compile time are Events occur at run time are

"Static Binding". "Dynamic Binding".

Information All information needed to call a All information need to call a

function is known at compile function come to know at run

time. time.

Advantage Efficiency. Flexibility.

Time Fast execution. Slow execution.

Alternate name Early Binding. Late Binding.

Example Overloaded function call, Virtual function in C++,

overloaded operators. overridden methods in java.


CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

Loops in JavaScript
Looping in programming languages is a feature which facilitates the execution of a set
of instructions/functions repeatedly while some condition evaluates to true. For
example, suppose we want to print “Hello World” 10 times. This can be done in two
ways as shown below:
Iterative Method
Iterative method to do this is to write the document.write() statement 10 times.

Loops in JavaScript

Loops are used to execute a specific statement for a given number of times. Loops are always
followed by some condition. JavaScript provides all the basic loops that other programming
languages have.

while loop
while loop checks for a given condition to be true to execute statements that it contains within it.
When the condition becomes false, while loop break the execution of statements.

Syntax

initializer;

while(condition)

statement-1;

statement-2;

.....

modifier;

initializer is a variable that is tested within the condition. modifier modifies the initializer so that
the condition becomes false at some point.

Note: Make sure that your condition goes false somehow else you will be in an infinite loop.

VAPM,Almala Page 1
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

Example

<script>

var i = 0;

while(i<6)

document.write(i);

document.write("<br />");

i++;

</script>

do while loop
do while loop first execute the statements that it contain and then check for a condition. So even
if the condition is false do-while loop is going to run at least once.

Syntax

initializer;

do

statement-1;

statement-2;

.....

modifier;

VAPM,Almala Page 2
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

while(condition);

Example

<script>

var i = 5;

do

document.write(i);

document.write("<br />");

i++;

while(i<6);

</script>

for loop
for loop is generally used when the number of iterations/repetitions are already known. Its not
that such tasks can't be done by while loop but its just a matter of preference.

Syntax

for(initializer; condition; modifier)

VAPM,Almala Page 3
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

statement-1;

.....

Here, initializer is a variable that is defined once in the beginning of a for loop. It is optional and can be
ignored. condition is checked after initialization. Then statements are executed and finally modifier
modifies the initializer. After that again condition is checked and the process continues. Modifier can also
be ignored.

Note: The only required thing within for loop is condition.

You can drop the curly braces if only one statement is within the for loop.

Syntax

<script>

for(var i=0;i<10;i++)

document.write(i);

document.write("<br />");

</script>

Nested Loops
Any loop can be inserted inside any other loop. This is called nesting. for loop can be nested
inside while or for loop. Similarly while loop can be nested inside for loop or another while loop.

Syntax

for(initializer; condition; modifier)

VAPM,Almala Page 4
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

while(condition)

statements;

Example

<script>

var i,j;

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

document.write("Outer Loop : " + i);

document.write("<br />");

for(j=0;j<3;j++)

document.write("Inner Loop : " + j);

document.write("<br />");

document.write("<br />");

VAPM,Almala Page 5
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

/*************output***************

Outer Loop : 0

Inner Loop : 0

Inner Loop : 1

Inner Loop : 2

Outer Loop : 1

Inner Loop : 0

Inner Loop : 1

Inner Loop : 2

Outer Loop : 2

Inner Loop : 0

Inner Loop : 1

Inner Loop : 2

***********************************/

</script>

Can you guess how above loop works? First outer for loop initializes i, checks for the condition
then executes its first two statements. After that inner for loop starts to work. After executing its
statements 3 times, outer for loop is given the control again. And the process is repeated.

VAPM,Almala Page 6
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

Loops Control Statements in JavaScript

Loop control statements deviates a loop from its normal flow. All the loop control statements are
attached to some condition inside the loop.

break statement
break statement is used to break the loop on some condition.

Syntax

for(initializer, condition, modifier)

if(condition)

break;

statements;

//same thing is valid for while loop

while(condition)

if(condition)

break;

VAPM,Almala Page 7
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

statements;

Example

<script>

for(var i=1;i<10;i++)

if(i===7) break;

document.write(i + "<br />");

/**********output***********

***************************/

</script>

VAPM,Almala Page 8
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

for loop should print from 1 - 10. But inside loop we have given a condition that if value of i
equals to 7, then break out of loop. I have left the curly braces within the if condition because
there is only one statement to be executed.

Remember break burst the nearest for loop within which it is contained. To understand what
it means check out the next example.

Example

<script>

for(var i=1;i<=3;i++)

document.write("Outer Loop : " + i + "<br />");

for(var j=1;j<=3;j++)

document.write("Inner Loop : " + j + "<br />");

if(j===2)

break;

document.write("<br />");

VAPM,Almala Page 9
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

/**********output***********

Outer Loop : 1

Inner Loop : 1

Inner Loop : 2

Outer Loop : 2

Inner Loop : 1

Inner Loop : 2

Outer Loop : 3

Inner Loop : 1

Inner Loop : 2

***************************/

</script>

continue statement
continue statement is used to skip an iteration of a loop.

Syntax

for(initializer, condition, modifier)

if(condition)

VAPM,Almala Page 10
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

continue;

statements;

//same thing is valid for while loop

while(condition)

if(condition)

continue;

statements;

Example

<script>

for(var i=0;i<10;i++)

if(i===3 || i===7) continue;

document.write(i + "<br />");

VAPM,Almala Page 11
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

/**********output***********

***************************/

</script>

In the code above when the value of i becomes 3 or 7, continue forces the loop to skip without
further executing any instructions inside the for loop in that current iteration.

Remember continue skips the nearest loop iteration within which it is contained. To
understand what it means check out the next example.

Example

<script>

for(var i=1;i<=3;i++)

VAPM,Almala Page 12
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

document.write("Outer Loop : " + i + "<br />");

for(var j=1;j<=3;j++)

if(j===2)

continue;

document.write("Inner Loop : " + j + "<br />");

document.write("<br />");

/**********output***********

Outer Loop : 1

Inner Loop : 1

Inner Loop : 3

Outer Loop : 2

Inner Loop : 1

Inner Loop : 3

VAPM,Almala Page 13
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

Outer Loop : 3

Inner Loop : 1

Inner Loop : 3

***************************/

</script>

When value of j inside inner loop becomes 2, it skips that iteration.

Mathematical Constants in JavaScript


Math object in JavaScript provides various mathematical constants and mathematical functions.
Below is the list of various constants.

Constant Description Value

Math.PI Constant PI 3.141592653589793

Math.E Euler's Constant 2.718281828459045

Math.LN2 Natural log of 2 0.6931471805599453

Math.LN10 Natural log of 10 2.302585092994046

Math.LOG2E Base 2 log of E 1.4426950408889634

Math.LOG10E Base 10 log of E 0.4342944819032518

Math.SQRT1_2 Square root of 0.5 0.7071067811865476

Math.SQRT2 Squre root of 2 1.4142135623730951

Example

VAPM,Almala Page 14
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

<script>

var x = Math.PI;

document.write(x); //outputs 3.141592653589793

</script>

Commonly used Mathematical Methods in JavaScript


Some commonly used methods that are used mostly in JavaScript are as follows:

Method Description

Math.abs(number) returns an absolute value

Math.sqrt(number) returns square root of a number

Math.pow(a, b) returns power value a raised to the power b

Math.log(number) returns natural log value

Math.exp(number) returns Euler's contsant raised to power of specified number

Math.max(a, b) returns larger of two numbers

Math.min(a, b) returns smaller of two numbers

Example

<script>

VAPM,Almala Page 15
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

var a = Math.abs(-7); //7

document.write(a);

document.write("<br />");

a = Math.sqrt(64); //8

document.write(a);

document.write("<br />");

a = Math.pow(2, 3); //2x2x2 = 8

document.write(a);

document.write("<br />");

a = Math.log(20); //2.995732273553991

document.write(a);

document.write("<br />");

a = Math.exp(5); //148.41315910257657

document.write(a);

document.write("<br />");

a = Math.max(5,10); //10

VAPM,Almala Page 16
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

document.write(a);

document.write("<br />");

a = Math.min(5,10); //5

document.write(a);

document.write("<br />");

a = Math.min(-50,-49); //-50

document.write(a);

</script>

Trigonometric Methods in JavaScript


Trignometric Methods are rarely used but still sometimes helpful. Some of the trigonometric
methods used are given below:

Method Description

Math.sin(number) returns sine value

Math.cos(number) returns cosine value

Math.tan(number) returns tangent value

Math.asin(number) returns arc sine value

Math.acos(number) returns arc cosine value

VAPM,Almala Page 17
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

Math.atan(number) returns arc tangent value

Example

<script>

var a = Math.sin(0); //sin 0 degree = 0

document.write(a);

document.write("<br />");

a = Math.cos(0); //cos 0 degree = 1

document.write(a);

document.write("<br />");

a = Math.tan(0); //tan 0 degree = 0

document.write(a);

</script>

Rounding Numbers in JavaScript


You can round off numbers using the functions given in the table.

Method Description

Math.ceil(number) returns rounded up integer value

VAPM,Almala Page 18
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

Math.floor(number) returns rounded down integer value

Math.round(number) returns nearest integer value

Example

<script>

var a = Math.ceil(12.4); //13

document.write(a);

document.write("<br />");

a = Math.floor(12.4); //12

document.write(a);

document.write("<br />");

a = Math.round(12.4); //12

document.write(a);

document.write("<br />");

a = Math.round(12.5); //13

document.write(a);

</script>

VAPM,Almala Page 19
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

Rounding Number up to specific level of precision in JavaScript


While rounding a number using round() method, you will always end up getting some integer.
Not all the time you want this. Sometimes you need to get a value up to some specific decimal
level or precision. For example, Math.PI returns 3.141592653589793. What if you want to get
this value up to 2 decimal places (3.14)? For doing so, you can multiply the floating point
number with 100. Then use the round() method and then divide the number again by 100. Below
is a formula that you can use.

Syntax

(Math.round(number * precision factor)) / precision factor

Precision factor represents the decimal level and is equal to 10 raise to the power of the decimal
places. For example if you want 2 decimal places, precision factor will be 100(10^2), for 3
decimal places it should be 1000(10^3).

Example

<script>

var p = Math.round(Math.PI); //3

document.write(p);

document.write("<br />");

//for 2 decimal places

var p = Math.PI * 100;

p = Math.round(p);

p /= 100;

document.write(p);

document.write("<br />");

VAPM,Almala Page 20
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

//for 4 decimal places

var p = (Math.round(Math.PI * 10000))/10000;

document.write(p);

</script>

Random Number in JavaScript


Math.random() method is used to generate a random floating point number between 0.0 and
1.0. You can always increase its range by multiplying it to a number. For example, multiplying it
with 10 will increase its range from 0.0 to 10.0. And to get an integer range, use Math.ceil() so
that the range actually becomes 1 to 10. You can use Math.floor() to make the range between 0
and 9.

Syntax

Math.random();

Example

<script>

var r = Math.random();

r *= 10;

r = Math.ceil(r); //returns any number between 1-10

document.write(r);

document.write("<br />");

VAPM,Almala Page 21
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

r = Math.floor(Math.random()*10); //returns any number between 0-9

document.write(r);

</script>

Infinity in JavaScript
Infinity is a global property (variable) that is used to represent infinite values in JavaScript.

Example

<script>

var i = 100 / 0;

document.write(i); //Infinity

</script>

There are also two other global properties in JavaScript, POSITIVE_INFINITY and
NEGATIVE_INFINITY but they are rarely used.

NaN in JavaScript
NaN is a global property which means "Not a Number".

Example

<script>

var n = "string" * 10; //NaN

document.write(n);

VAPM,Almala Page 22
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

</script>

Working with Strings in JavaScript

String plays an important role in every programming languages. JavaScript is no exception. Also
every character in JavaScript is represented by some number. That numerical unicode is known
as charcode of that character. Example, 'A' is represented by 65.

Here are few functions that can be useful to help you out with your day to day coding work.

String Concatenation
String concatenation refers to combining one string to another. Simplest way to join strings is
using '+' (plus) operator. But there is also a method concat() which can be used to unite strings
together.

Syntax

//using concat method

string1.concat(string2, string3, ...);

//using + operator

string1 + string2 + string3

Example

<script>

var str = "Syntax";

str = str.concat("Page"); //SyntaxPage

document.write(str);

VAPM,Almala Page 23
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

document.write("<br />");

str = "JavaScript";

str = str.concat(" is", " fun", "<br />");

document.write(str); //JavaScript is fun

str = "JavaScript " + "is " + "awesome" + "<br />";

document.write(str); //JavaScript is awesome

</script>

Splitting Strings
Various methods are available in JavaScript to get whole or some part of strings. Few commonly
used methods are as follows:

substring() method
substring method is used to get arbitrary string values between the index positions passed to it as
parameters.

Syntax

string.substring(start,[end])

First parameter specifies from where to copy the string. Second optional parameter specifies till
where to copy. Also, character specified by second parameter is not included. If second
parameter is not given then whole string after start position will be copied.

Example

<script>

VAPM,Almala Page 24
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

var str = 'SyntaxPage';

var sub = str.substring(6); //Page

document.write(sub);

document.write("<br />)

str = 'JavaScript';

sub = str.substring(4,7); //Src

document.write(sub);

//element at 4th position is excluded

</script>

substr() method
substr method is somewhat similar to substring() method with just one difference. The second
parameter in the substr() method specifies the length of the string to be copied, not the end
position.

Syntax

string.substr(start,length)

Example

<script>

VAPM,Almala Page 25
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

var str = 'SyntaxPage';

var sub = str.substr(6); //Page

document.write(sub);

document.write("<br />")

str = 'JavaScript';

sub = str.substr(4,3); //Scr

document.write(sub);

</script>

slice() method
slice method is used to get characters from a string between specified indexes passed to it as
parameters.

Syntax

string.slice(start, [end])

The element at the 'end' index is not included. If end index is not specified then the result will be
from start index till the end of the string.

Example

<script>

var str = "12345";

VAPM,Almala Page 26
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

var sub = str.slice(1, 4); //234

document.write(sub);

document.write("<br />");

sub = str.slice(1); //2345

document.write(sub);

</script>

split() method
split() method breaks a string into an array of string. It splits the string from the separator string
boundaries that is passed to it as parameter.

Syntax

string.split(separator,[size])

If no separator string is given then it will break the string into an array having just one element
which is string itself.

If optional size parameter is given then array formed will be of given size parameter ignoring the
rest of the characters.

Example

<script>

var str = "JavaScript is fun";

var sub = str.split(" ");

VAPM,Almala Page 27
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

document.write(sub); //JavaScript,is,fun

document.write("<br />");

sub = str.split(" ", 1);

document.write(sub); //JavaScript

document.write("<br />");

sub = str.split();

document.write(sub[0]); //JavaScript is fun

</script>

Changing Case
toLowerCase() method
toLowerCase() method is used to change the case of the string to lower case.

Syntax

string.toLowerCase()

Example

<script>

var str = "JavaScript is Awesome";

var lcase = str.toLowerCase();

VAPM,Almala Page 28
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

document.write(lcase);

</script>

toUpperCase() method
toUpperCase() method is used to change the case of the string to upper case.

Syntax

string.toUpperCase()

Example

<script>

var str = "JavaScript is Awesome";

var ucase = str.toUpperCase();

document.write(ucase);

</script>

Finding Characters
indexOf() method
indexOf() method is used to search for a given substring in the parent string and returns substring
position.

Syntax

VAPM,Almala Page 29
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

string.indexOf(needle,[fromIndex])

Optional second parameter decides from where to begin searching the string. It starts searching
from the beginning if optional second parameter is not given. In case needle(substring) is not
found then it returns -1.

Example

<script>

var str = "JavaScript is an Awesome Script";

var pos = str.indexOf("Script"); //4

document.write(pos);

document.write("<br />");

var pos = str.indexOf("Script",5); //25

document.write(pos);

</script>

lastIndexOf() method
lastIndexOf() method is used to search for a given substring beginning the search from the end. It
returns needle's position. In case needle(substring) is not found then it returns -1.

Syntax

string.lastIndexOf(needle,[fromIndex])

VAPM,Almala Page 30
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

It starts searching from the end if optional second parameter is not given. In case
needle(substring) is not found then it returns -1.

Example

<script>

var str = "JavaScript is an Awesome Script";

var pos = str.lastIndexOf("Script"); //25

document.write(pos);

var pos = str.lastIndexOf("Script",24); //4

document.write(pos);

</script>

search() method
search() returns the index position of the needle if found else it returns -1. It looks somewhat
similar to indexOf() method but seach() method works with regular expressions. Regular
expressions will be discussed later.

Syntax

string.search(regexp)

Example

<script>

VAPM,Almala Page 31
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

var str = "JavaScript is an Awesome Script";

var pos = str.search("Script"); //4

document.write(pos);

</script>

match() method
match() returns the substring(needle) if found in the main string else it returns null. match()
method also works with regular expressions. Performance wise indexOf() method is faster than
match() and search().

Syntax

string.match(regexp)

Example

<script>

var str = "JavaScript is an Awesome Script";

var pos = str.match("Script"); //Script

document.write(pos);

</script>

charAt() method

VAPM,Almala Page 32
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

charAt() returns the character at a particular index which is passed to it as an argument.

string.charAt(index)

Example

<script>

var str = "JavaScript is an Awesome Script";

var c = str.charAt(4); //S

document.write(c);

</script>

charCodeAt() method
charCodeAt() returns the unicode numeric value of a character at a particular index which is
passed to it as an argument.

string.charAt(index)

Example

<script>

var str = "JavaScript is an Awesome Script";

var u = str.charCodeAt(4); //83

document.write(u);

VAPM,Almala Page 33
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

</script>

Replacing word in a string


replace() method
replace() method is used to find and replace some or all occurrence of a string/character with
some new specified string/character within a string. To replace more than one value within a
string pass regular expression as first argument.

Syntax

string.replace(regular_expression/string, 'new_string')

Example

<script>

var str = "JavaScript is Awesome";

var newStr = str.replace("Awesome", "Amazing");

document.write(newStr);

</script>

Summary of String Methods in JavaScript

Method Description

str.concat(str1, str2,...) combines one or more string

str.substring(start,[end]) returns substring from start to end unless end index position

VAPM,Almala Page 34
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

is specified

returns substring from start to end unless number of


str.substr(start,len)
characters(length) is specified

str.slice(start, [end]) returns substring between specified indexes

breaks a string into an array from the separator string


str.split(sep,[size])
boundaries

str.toLowerCase() returns lowercase string

str.toUpperCase() returns uppercase string

returns character present at specified index beginning the


str.indexOf(needle,[fromIndex]) search from start. Second parameter decides from where to
begin search

returns character present at specified index beginning the


str.lastIndexOf(needle,[fromIndex]) search from end. Second parameter decides from where to
begin search

returns the index position of the substring if found else it


str.search(regexp)
returns -1

str.match(regexp) returns the substring if found else it returns null.

returns the character at a particular index which is passed to


str.charAt(index)
it as an argument

returns the unicode numeric value of a character at a


str.charCodeAt(index)
particular index which is passed to it as an argument

str.replace(regular_expression/string, returns string after replacing some or all occurrence of old


"new_string") string with new string within a given string.

VAPM,Almala Page 35
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

Date and Time in JavaScript

Date object in JavaScript can be used to get date and time. Date object has various methods to
exploit date and time. To get date and time use new keyword followed by with Date object
constructor.

Syntax

//get date and time

new Date();

//set date and time

new Date(year, month, date, hours, minutes, seconds, milliseconds);

Example

<script>

var now = new Date();

document.write(now);

//Fri Feb 20 2015 21:12:09 GMT+0530 (India Standard Time)

document.write('<br />');

now = new Date(2005, 11, 21, 12, 30, 30, 0);

document.write(now);

VAPM,Almala Page 36
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

//Wed Dec 21 2005 12:30:30 GMT+0530 (India Standard Time)

</script>

Working with Date


To get and set date, Date objects has various methods.

date.getDay() returns the day number (0-6, 0 for sun, 1 for mon and so on)

date.getDate() returns the date (1 to 31)

date.getMonth() returns the month (0-11, 0 for jan and so on)

date.getFullYear() returns 4 digit year

date.setDate(value) sets the date (1 to 31)

date.setMonth(value) sets the month (0-11, 0 for jan and so on)

date.setFullYear() sets 4 digit year

Example

<script>

var days = ['Sun', 'Mon', 'Tues', 'Wed', 'Thu', 'Fri', 'Sat'];

var months = ['Jan', 'Feb', 'March', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

VAPM,Almala Page 37
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

var d = new Date();

var day = d.getDay();

day = days[day];

var date = d.getDate();

var month = d.getMonth();

month = months[month];

var year = d.getFullYear();

document.write(day + " " + date + " " + month + " " + year);

</script>

Working with Time


To get and set time, Date objects has various methods.

date.getHours() returns hour in 24-hour format (0-23)

date.getMinutes() returns minute (0-59)

date.getSeconds() returns second (0-59)

VAPM,Almala Page 38
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

date.getMilliseconds() returns millisecond (0-999)

date.setHours() sets hour in 24-hour format (0-23)

date.setMinutes() sets minute (0-59)

date.setSeconds() sets second (0-59)

date.setMilliseconds() sets millisecond (0-999)

Example

<script>

var t = new Date();

var hour = t.getHours();

var min = t.getMinutes();

var sec = t.getSeconds();

var milli = t.getMilliseconds();

document.write(hour + ":" + min + ":" + sec + ":" + milli);

VAPM,Almala Page 39
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

</script>

Working with Strings in JavaScript

String plays an important role in every programming languages. JavaScript is no exception. Also
every character in JavaScript is represented by some number. That numerical unicode is known
as charcode of that character. Example, 'A' is represented by 65.

Here are few functions that can be useful to help you out with your day to day coding work.

String Concatenation
String concatenation refers to combining one string to another. Simplest way to join strings is
using '+' (plus) operator. But there is also a method concat() which can be used to unite strings
together.

Syntax

//using concat method

string1.concat(string2, string3, ...);

//using + operator

string1 + string2 + string3

Example

<script>

var str = "Syntax";

str = str.concat("Page"); //SyntaxPage

document.write(str);

document.write("<br />");

VAPM,Almala Page 40
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

str = "JavaScript";

str = str.concat(" is", " fun", "<br />");

document.write(str); //JavaScript is fun

str = "JavaScript " + "is " + "awesome" + "<br />";

document.write(str); //JavaScript is awesome

</script>

Splitting Strings
Various methods are available in JavaScript to get whole or some part of strings. Few commonly
used methods are as follows:

substring() method
substring method is used to get arbitrary string values between the index positions passed to it as
parameters.

Syntax

string.substring(start,[end])

First parameter specifies from where to copy the string. Second optional parameter specifies till
where to copy. Also, character specified by second parameter is not included. If second
parameter is not given then whole string after start position will be copied.

Example

<script>

VAPM,Almala Page 41
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

var str = 'SyntaxPage';

var sub = str.substring(6); //Page

document.write(sub);

document.write("<br />)

str = 'JavaScript';

sub = str.substring(4,7); //Src

document.write(sub);

//element at 4th position is excluded

</script>

substr() method
substr method is somewhat similar to substring() method with just one difference. The second
parameter in the substr() method specifies the length of the string to be copied, not the end
position.

Syntax

string.substr(start,length)

Example

<script>

var str = 'SyntaxPage';

VAPM,Almala Page 42
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

var sub = str.substr(6); //Page

document.write(sub);

document.write("<br />")

str = 'JavaScript';

sub = str.substr(4,3); //Scr

document.write(sub);

</script>

slice() method
slice method is used to get characters from a string between specified indexes passed to it as
parameters.

Syntax

string.slice(start, [end])

The element at the 'end' index is not included. If end index is not specified then the result will be
from start index till the end of the string.

Example

<script>

var str = "12345";

var sub = str.slice(1, 4); //234

VAPM,Almala Page 43
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

document.write(sub);

document.write("<br />");

sub = str.slice(1); //2345

document.write(sub);

</script>

split() method
split() method breaks a string into an array of string. It splits the string from the separator string
boundaries that is passed to it as parameter.

Syntax

string.split(separator,[size])

If no separator string is given then it will break the string into an array having just one element
which is string itself.

If optional size parameter is given then array formed will be of given size parameter ignoring the
rest of the characters.

Example

<script>

var str = "JavaScript is fun";

var sub = str.split(" ");

document.write(sub); //JavaScript,is,fun

VAPM,Almala Page 44
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

document.write("<br />");

sub = str.split(" ", 1);

document.write(sub); //JavaScript

document.write("<br />");

sub = str.split();

document.write(sub[0]); //JavaScript is fun

</script>

Changing Case
toLowerCase() method
toLowerCase() method is used to change the case of the string to lower case.

Syntax

string.toLowerCase()

Example

<script>

var str = "JavaScript is Awesome";

var lcase = str.toLowerCase();

document.write(lcase);

VAPM,Almala Page 45
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

</script>

toUpperCase() method
toUpperCase() method is used to change the case of the string to upper case.

Syntax

string.toUpperCase()

Example

<script>

var str = "JavaScript is Awesome";

var ucase = str.toUpperCase();

document.write(ucase);

</script>

Finding Characters
indexOf() method
indexOf() method is used to search for a given substring in the parent string and returns substring
position.

Syntax

string.indexOf(needle,[fromIndex])

VAPM,Almala Page 46
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

Optional second parameter decides from where to begin searching the string. It starts searching
from the beginning if optional second parameter is not given. In case needle(substring) is not
found then it returns -1.

Example

<script>

var str = "JavaScript is an Awesome Script";

var pos = str.indexOf("Script"); //4

document.write(pos);

document.write("<br />");

var pos = str.indexOf("Script",5); //25

document.write(pos);

</script>

lastIndexOf() method
lastIndexOf() method is used to search for a given substring beginning the search from the end. It
returns needle's position. In case needle(substring) is not found then it returns -1.

Syntax

string.lastIndexOf(needle,[fromIndex])

It starts searching from the end if optional second parameter is not given. In case
needle(substring) is not found then it returns -1.

Example

VAPM,Almala Page 47
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

<script>

var str = "JavaScript is an Awesome Script";

var pos = str.lastIndexOf("Script"); //25

document.write(pos);

var pos = str.lastIndexOf("Script",24); //4

document.write(pos);

</script>

search() method
search() returns the index position of the needle if found else it returns -1. It looks somewhat
similar to indexOf() method but seach() method works with regular expressions. Regular
expressions will be discussed later.

Syntax

string.search(regexp)

Example

<script>

var str = "JavaScript is an Awesome Script";

var pos = str.search("Script"); //4

VAPM,Almala Page 48
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

document.write(pos);

</script>

match() method
match() returns the substring(needle) if found in the main string else it returns null. match()
method also works with regular expressions. Performance wise indexOf() method is faster than
match() and search().

Syntax

string.match(regexp)

Example

<script>

var str = "JavaScript is an Awesome Script";

var pos = str.match("Script"); //Script

document.write(pos);

</script>

charAt() method
charAt() returns the character at a particular index which is passed to it as an argument.

string.charAt(index)

VAPM,Almala Page 49
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

Example

<script>

var str = "JavaScript is an Awesome Script";

var c = str.charAt(4); //S

document.write(c);

</script>

charCodeAt() method
charCodeAt() returns the unicode numeric value of a character at a particular index which is
passed to it as an argument.

string.charAt(index)

Example

<script>

var str = "JavaScript is an Awesome Script";

var u = str.charCodeAt(4); //83

document.write(u);

</script>

Replacing word in a string


VAPM,Almala Page 50
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

replace() method
replace() method is used to find and replace some or all occurrence of a string/character with
some new specified string/character within a string. To replace more than one value within a
string pass regular expression as first argument.

Syntax

string.replace(regular_expression/string, 'new_string')

Example

<script>

var str = "JavaScript is Awesome";

var newStr = str.replace("Awesome", "Amazing");

document.write(newStr);

</script>

Summary of String Methods in JavaScript

Method Description

str.concat(str1, str2,...) combines one or more string

returns substring from start to end unless end index position


str.substring(start,[end])
is specified

returns substring from start to end unless number of


str.substr(start,len)
characters(length) is specified

str.slice(start, [end]) returns substring between specified indexes

VAPM,Almala Page 51
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

breaks a string into an array from the separator string


str.split(sep,[size])
boundaries

str.toLowerCase() returns lowercase string

str.toUpperCase() returns uppercase string

returns character present at specified index beginning the


str.indexOf(needle,[fromIndex]) search from start. Second parameter decides from where to
begin search

returns character present at specified index beginning the


str.lastIndexOf(needle,[fromIndex]) search from end. Second parameter decides from where to
begin search

returns the index position of the substring if found else it


str.search(regexp)
returns -1

str.match(regexp) returns the substring if found else it returns null.

returns the character at a particular index which is passed to


str.charAt(index)
it as an argument

returns the unicode numeric value of a character at a


str.charCodeAt(index)
particular index which is passed to it as an argument

str.replace(regular_expression/string, returns string after replacing some or all occurrence of old


"new_string") string with new string within a given string.

Different Types of Conditional Statements


There are mainly three types of conditional statements in JavaScript.

1. If statement
2. If…Else statement
3. If…Else If…Else statement

VAPM,Almala Page 52
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

If statement
Syntax:

if (condition)

lines of code to be executed if condition is true

You can use If statement if you want to check only a specific condition.

Try this yourself:


This code is editable. Click Run to Execute

<html>

<head>

<title>IF Statments!!!</title>

<script type="text/javascript">

var age = prompt("Please enter your age");

if(age>=18)

document.write("You are an adult <br />");

if(age<18)

document.write("You are NOT an adult <br />");

</script>

VAPM,Almala Page 53
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

</head>

<body>

</body>

</html>

VAPM,Almala Page 54
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

What is JavaScript?

JavaScript is a scripting language that is created for showing HTML pages live. JavaScript does
not require any compilation. It is interpreted language. JavaScript can modify HTML page, write
text in it, add or remove tags, change styles etc.

JavaScript code can get to execute on events, mouse clicks, and movements, keyboard input etc.
It can send the request to the server and load data without reloading of the page. This technology
is often called “AJAX”. JavaScript makes the web pages dynamic.

Advantages of JavaScript

 Adding new HTML to the page, change the existing content, modify styles.
 React to the user actions, run on mouse clicks, pointer movements, key presses.
 Send requests through the network to remote servers, download and upload files. It is called
AJAX and COMET Technologies.

In this JavaScript tutorial, we will learn different JavaScript Features and how we inculcate it
in writing HTML pages. It gives insight about how modern features of JavaScript are widely
used.
We will discuss different unique features of JavaScript and various features of Modern
JavaScript with examples.

Core Features of JavaScript

Various features of JavaScript are as follows:

1. Client – Side Technology

JavaScript is a client-side technology. It is mainly used for giving client-side validation. It is an


object-based scripting language.

2. Greater Control

It gives the user more control over the browser.

Example – You can change the background color of the page as well as text on the browser’s
status bar.
Here, the back button is implemented with JavaScript. Click it and you will return to the page
from which you have arrived.

3. Detecting the User’s Browser and OS.

The feature to detect the user’s browser and OS enables your script to perform platform–
dependent operations.

VAPM,Almala Page 1
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

4. Performing Simple Calculation on the Client side

Using a JavaScript calculator, we perform simple calculations on the client side.

5. Validating The User’s Input

In the JavaScript calculator, try to type some letters instead of numeric input, you will get an
error: Invalid input character. Note that, JavaScript helps the browser perform output validation
without wasting the user’s time by the web server access.

If the user makes a mistake in the input, the user will get an error message immediately. If the
input information is validated only on the server, then the user would have to wait for the
server’s response.

6. Handling Date and time

The JavaScript says, “Nice Morning, isn’t it? Or “Good Afternoon”, depending on the current
time. It also tells you today’s date.

Nice Morning isn’t it? Today is Wednesday, 20 February 2019.

7. Generating HTML on the Fly

Every time you click on the button, the browser generates and displays a new HTML code.
Thanks to JavaScript, this operation performs on the client- machine and therefore you don’t
have to wait while the information backs and forth between your browser and the web server.

8. Semicolon Insertion

All statements in JavaScript must terminate with a semicolon. Most of the JavaScript control
statements syntax is the same as control statements in C.

JavaScript Objects

A javaScript object is an entity having state and behavior (properties and method). For example:
car, pen, bike, chair, glass, keyboard, monitor etc.

JavaScript is an object-based language. Everything is an object in JavaScript.

JavaScript is template based not class based. Here, we don't create class to get the object. But, we
direct create objects.

Creating Objects in JavaScript

There are 3 ways to create objects.

1. By object literal

VAPM,Almala Page 2
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

2. By creating instance of Object directly (using new keyword)


3. By using an object constructor (using new keyword)

1) JavaScript Object by object literal

The syntax of creating object using object literal is given below:

1. object={property1:value1,property2:value2.....propertyN:valueN}

As you can see, property and value is separated by : (colon).

Let’s see the simple example of creating object in JavaScript.

<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

2) By creating instance of Object

The syntax of creating object directly is given below:

var objectname=new Object();

Here, new keyword is used to create object.

Let’s see the example of creating object directly.

<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

3) By using an Object constructor

Here, you need to create function with arguments. Each argument value can be assigned in the
current object by using this keyword.

The this keyword refers to the current object.

VAPM,Almala Page 3
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

The example of creating object by object constructor is given below.

<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);


</script>
Output of the above example
103 Vimal Jaiswal 30000

Defining method in JavaScript Object

We can define method in JavaScript object. But before defining method, we need to add property
in the function with same name as method.

The example of defining method in object is given below.

<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;

this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
}
}
e=new emp(103,"Sonoo Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
e.changeSalary(45000);
document.write("<br>"+e.id+" "+e.name+" "+e.salary);
</script>

VAPM,Almala Page 4
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

JavaScript Object Methods

The various methods of Object are as follows:

S.No Methods Description

1 Object.assign() This method is used to copy enumerable


and own properties from a source object to
a target object

2 Object.create() This method is used to create a new object


with the specified prototype object and
properties.

3 Object.defineProperty() This method is used to describe some


behavioral attributes of the property.

4 Object.defineProperties() This method is used to create or configure


multiple object properties.

5 Object.entries() This method returns an array with arrays of


the key, value pairs.

6 Object.freeze() This method prevents existing properties


from being removed.

7 Object.getOwnPropertyDescriptor() This method returns a property descriptor


for the specified property of the specified
object.

8 Object.getOwnPropertyDescriptors() This method returns all own property


descriptors of a given object.

VAPM,Almala Page 5
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

9 Object.getOwnPropertyNames() This method returns an array of all


properties (enumerable or not) found.

10 Object.getOwnPropertySymbols() This method returns an array of all own


symbol key properties.

11 Object.getPrototypeOf() This method returns the prototype of the


specified object.

12 Object.is() This method determines whether two


values are the same value.

13 Object.isExtensible() This method determines if an object is


extensible

14 Object.isFrozen() This method determines if an object was


frozen.

15 Object.isSealed() This method determines if an object is


sealed.

16 Object.keys() This method returns an array of a given


object's own property names.

17 Object.preventExtensions() This method is used to prevent any


extensions of an object.

18 Object.seal() This method prevents new properties from


being added and marks all existing
properties as non-configurable.

19 Object.setPrototypeOf() This method sets the prototype of a


specified object to another object.

VAPM,Almala Page 6
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

20 Object.values() This method returns an array of values.

JavaScript Operators with Example


JavaScript Operators use either value or variable to compute some task. This lesson describes the
JavaScript operators with example, and operators precedence. JavaScript has following types
operators,

1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Conditional Operator (Ternary Operator)
6. Bitwise Operators
7. Miscellaneous Operators
1. typeof
2. delete
3. instanceof
4. new
5. this
6. in

JavaScript Operators with Example


JavaScript Arithmetic Operators
JavaScript arithmetic operator take operand (as a values or variable) and return the single value.

We are use in our routine life arithmetic operators, addition(+), subtraction(-), multiplication (*),
and division (/) and some other arithmetic operator are listed below.

We have numeric variable: x = 10, y = 5 and result.

Operator Description Example Results

+ Addition result = x + y result = 15

- Subtraction result = x - y result = 5

VAPM,Almala Page 7
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

* Multiplication result = x * y result = 50

/ Division result = x / y result = 2

% Modulus result = x % y result = 0

++ Increment result = x++ result = 10


result = x result = 11
result = ++x result = 12

-- Decrement result = x-- result = 12


result = x result = 11
result = --x result = 10

<script>
var x = 10, y = 5;
document.writeln(x + y); // Addition: 15
document.writeln(x - y); // Subtraction: 5
document.writeln(x * y); // Multiplication: 50
document.writeln(x / y); // Division: 2
document.writeln(x % y); // Modulus: 0

document.writeln(x++); // x: 10, x become now 11


document.writeln(x); // x: 11
document.writeln(++x); // x become now 12, x: 12

document.writeln(x--); // x: 12, x become now 11


document.writeln(x); // x: 11
document.writeln(--x); // x become now 10, x: 10
</script>

JavaScript Assignment Operators

VAPM,Almala Page 8
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

JavaScript assignment operators assign values to left operand based on right operand. equal (=)
operators is used to assign a values.

We have numeric variable: x = 10, y = 5 and result.

Operator Sign Description Example Equivalent to Results

Assignment = Assign value from one operand to result = x result = x result =


another operand value. 17

Addition += Addition of operands and finally assign result += result = result result =
to left operand. x +y 22

Subtraction -= Subtraction of operands and finally result -= result = result - result =


assign to left operand. y y 17

Multiplication *= Multiplication of operands and finally result *= result = result result =


assign to left operand. y *y 85

Division /= Division of operands and finally assign result /= result = result / result =
to left operand. y y 17

Modulus %= Modulus of operands and finally assign result %= result = result result =
to left operand. y %y 2

Bitwise AND &= AND operator compare two bits values result &= result = result result =
return a results of 1, If both bits are 1. y &y 0
otherwise return 0. =2&5
= 0000 0010 &
0000 0101
= 0000 0000 =
0

Bitwise OR |= OR operator compare two bits values result |= y result = result | result =
and return result of 1, If the bits are y 7
complementary. Otherwise return 0. =2|5
= 0000 0010 |
0000 0101
= 0000 0111 =

VAPM,Almala Page 9
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

Bitwise XOR ^= EXCLUSIVE OR operator compare result ^= result = result result =


two bits values and return a results of y ^y 2
1, If any one bits are 1 or either both =7^5
bits one. = 0000 0111 ^
0000 0101
= 0000 0010 =
2

Shift Left <<= Shift left operator move the bits to a result result = result result =
left side. <<= y <<= y 64
= 2 <<= 5
= 0000 0010
<<= 0100
0000
= 64

Shift Right >>= Shift left operator move the bits to a result result = result result =
left side. >>= y >>= y 2
= 2 >>= 5
= 0100 0000
>>= 0000
0010
=2

<script>
var x = 17, y = 5;
var result = x; // Assignment to left operand(result) base on right operand(y).
document.writeln(result);
document.writeln(result += x);
document.writeln(result -= y);
document.writeln(result *= y);
document.writeln(result /= y);
document.writeln(result %= y);

document.writeln(result &= y);

VAPM,Almala Page 10
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

result = 2; // Reassign value


document.writeln(result |= y);
document.writeln(result ^= y);

document.writeln(result <<= y);


document.writeln(result >>= y);
</script>
Run it... »

JavaScript Comparison Operators


JavaScript comparison operator determine the two operands satisfied the given condition.
Comparison operator return either true or false.

Operator Sign Description

Equal == If both operands are equal, returns true.

Identical equal === If both operands are equal and/or same data type, returns true.

Not equal != If both operands are not equal, returns true.

Identical not equal !== If both operands are not equal and/or same data type, returns true.

Greater than > If left operand larger than right operand, return true.

Less then < If left operand smaller than right operand, return true.

Greater than, equal >= If left operand larger or equal than right operand, return true.

Less than, equal <= If left operand smaller or equal than right operand, return true.

<script>
document.writeln(5 == 5); // true
document.writeln(5 == '5'); // true

VAPM,Almala Page 11
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

document.writeln(5 === '5'); // false type not same

document.writeln(5 != 10); // true


document.writeln(5 != '10'); // true
document.writeln(5 !== '10'); // true

document.writeln(5 > 10); // false


document.writeln(5 < 10); // true

document.writeln(5 >= 5); // true


document.writeln(5 <= 5); // true
</script>

JavaScript Logical Operators (Boolean Operators)


JavaScript logical operators return boolean result base on operands.

Operator Sign Description

Logical AND && If first operand evaluate and return a true, only that evaluate the second
operand otherwise skips.
Return true if both are must be true, otherwise return false.

Logical OR || Evaluate both operands,


Return true if either both or any one operand true,
Return false if both are false.

Logical NOT ! Return the inverse of the given value result true become false, and false
become true.

<script>
document.writeln((5 == 5) && (10 == 10)); // true
document.writeln(true && false); // false

document.writeln((5 == 5) || (5 == 10)); // true

VAPM,Almala Page 12
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

document.writeln(true || false); // true

document.writeln(5 && 10); // return 10


document.writeln(5 || 10); // return 5

document.writeln(!5); // return false


document.writeln(!true); // return false
document.writeln(!false); // return true
</script>
Run it... »

JavaScript Conditional Operator (also call Ternary Operator)


JavaScript conditional operator evaluate the first expression(operand), Base on expression result
return either second operand or third operand.
answer = expression ? answer1 : answer2; // condition ? true : false

Example
document.write((10 == 10) ? "Same value" : "different value");
Run it... »

JavaScript Bitwise Operators


JavaScript bitwise operators evaluate and perform specific bitwise (32 bits either zero or one)
expression.

Operator Sign Description

Bitwise AND & Return bitwise AND operation for given two operands.

Bitwise OR | Return bitwise OR operation for given two operands.

Bitwise XOR ^ Return bitwise XOR operation for given two operands.

Bitwise NOT ~ Return bitwise NOT operation for given operand.

VAPM,Almala Page 13
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

Bitwise Shift Left << Return left shift of given operands.

Bitwise Shift Right >> Return right shift of given operands.

Bitwise Unsigned Shift >>> Return right shift without consider sign of given operands.
Right

<script>
document.writeln(5 & 10); // return 0, calculation: 0000 0101 & 0000 1010 = 0000 0000
document.writeln(5 | 10); // return 15, calculation: 0000 0101 | 0000 1010 = 0000 1111
document.writeln(5 ^ 10); // return 15, calculation: 0000 0101 ^ 0000 1010 = 0000 1111
document.writeln(~5); // return -6, calculation: ~ 0000 0101 = 1111 1010

document.writeln(10 << 2); // return 40, calculation: 0000 1010 << 2 = 0010 1000
document.writeln(10 >> 2); // return 2, calculation: 0000 1010 >> 2 = 0000 0010
document.writeln(10 >>> 2); // return 2, calculation: 0000 1010 >>> 2 = 0000 0010
</script>
Run it... »

Miscellaneous Operators
1. typeof
2. delete
3. instanceof
4. new
5. this
6. in

typeof
JavaScript typeof operator return valid data type identifiers as a string of given
expression. typeof operator return six possible
values: "string", "number", "boolean", "object", "function", and "undefined".
typeof expression
typeof(expression)

Example

VAPM,Almala Page 14
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

var name = 'Opal Kole';


var age = 48;
var married = true;
var experience = [2010, 2011, 2012, 2013, 2014];
var message = function(){ console.log("Hello world!"); }
var address;

typeof name; // Returns "string"


typeof age; // Return "number"
typeof married; // Return "boolean"
typeof experience; // Return "object"
typeof message; // Return "function"
typeof address; // Return "undefined"
Run it... »

delete
JavaScript delete operator deletes object property or remove specific element in array.
If delete is not allow (you can't delete if element not exist, array element undefined etc..) then
return false otherwise return true.
delete expression; // delete explicit declare variable

delete object; // delete object


delete object.property;
delete object[property];

delete array; // delete array


delete array[index];

Example
var address = "63 street Ct.";
delete address; // Returns false, Using var keyword you can't delete
add = "63 street Ct.";
delete add; // Returns true, explicit declare you can delete

VAPM,Almala Page 15
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

var myObj = new Object();


myObj.name = "Opal Kole";
myObj.age = 48;
myObj.married = true;

delete myObj.name; // delete object property


delete myObj["count"]; // delete object property

var experience = [2010, 2011, 2012, 2013, 2014]; // array elements


delete experience[2]; // delete 2nd index from array elements
console.log(experience); // [2010, 2011, undefined × 1, 2013, 2014]
Run it... »

instanceof
JavaScript instanceof indicate boolean result, Return true, If object is an instance of specific
class.
object instanceof class

Example
<script>
var num1 = new Number(15);
document.writeln(num1 instanceof Number); // Returns true
var num2 = 10;
document.writeln(num2 instanceof Number); // Return false

document.writeln(true instanceof Boolean); // false


document.writeln(0 instanceof Number); // false
document.writeln("" instanceof String); // false

document.writeln(new Boolean(true) instanceof Boolean); // true


document.writeln(new Number(0) instanceof Number); // true
document.writeln(new String("") instanceof String); // true

VAPM,Almala Page 16
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

</script>
Run it... »

new
JavaScript new operator to create an instance of the object.
var myObj = new Object;
var myObj = new Object( ); // or you can write
// Object - required, for constructor of the object.

var arr = new Array( [ argument1, argument2, ..., ..., argumentN ] );


// argument - optional, pass any number of argument in a object.

Example
var myObj = new Object(); // or you can write: var myObj = new Object;
myObj.name = "Opal Kole";
myObj.address = "63 street Ct.";
myObj.age = 48;
myObj.married = true;

console.log(myObj);
// Object {name: "Opal Kole", address: "63 street Ct.", age: 48, married: true}
Run it... »

this
JavaScript this operator represent current object.
this["propertyname"]
this.propertyname

Example
function employee(name, address, age, married) {
this.name = name;
this.address = address;
this.age = age;
this.married = married;

VAPM,Almala Page 17
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

}
var myObj = new employee("Opal Kole", "63 street Ct.", 48, true);
console.log(myObj);
// employee {name: "Opal Kole", address: "63 street Ct.", age: 48, married: true}
Run it... »

in
JavaScript in operator return boolean result if specified property exist in object.
property in object

Example
<script>
var myObj = new Object(); // or you can write: var myObj = new Object;
myObj.name = "Opal Kole";
myObj.address = "63 street Ct.";
myObj.age = 48;
myObj.married = true;

document.writeln("name" in myObj); // Returns true


document.writeln("birthdate" in myObj); // Returns false
// birthdate propery not in myObj
document.writeln("address" in myObj); // Returns true
document.writeln("age" in myObj); // Returns true
document.writeln("married" in myObj); // Returns true
</script>
Like other languages, JavaScript also provides many decision making statements like if, else etc.

if statement
if is used to check for a condition whether its true or not. Condition could be any expression that
returns true or false. When condition satisfies then statements following if statement are
executed.

Syntax

if(condition)

VAPM,Almala Page 18
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

statement1

statement2

...

If you have only one statement to be executed after the if condition then you can drop the curly
braces ({ }). For more than one statement use curly braces.

if(condition)

statement

But still its good practice to use curly braces. It will help to easily manage and understand your
code.

Example

<script>

if(5>4)

document.write("yes 5 is greater than 4");

document.write("<br />" + "JavaScript is fun");

document.write("<br />");

/********outputs*********

yes 5 is greater than 4

VAPM,Almala Page 19
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

JavaScript is fun

************************/

if(true)

document.write("Ah! a boolean inside condition. Also no curly braces");

//see it works without curly braces

/********outputs*********

Ah! a boolean inside condition. Also no curly braces

************************/

if(1===3)

document.write("This will not be printed");

//since condition is false the statements within if will not be executed.

</script>

else statement
else statements are used with if statements. When if condition gets fail then else statement is
executed.

Syntax

if(condition)

VAPM,Almala Page 20
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

statements

else

statements

You can drop off the curly braces with else too if there is a single statement to be executed
within else.

Example

<script>

if(3>4)

document.write("True");

else

document.write("False");

//outputs False

VAPM,Almala Page 21
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

</script>

else if statement
Suppose there are variety of conditions that you want to check. You can use multiple if
statements to do this task. All the if conditions will be checked one by one. But what if you want
that if one condition satisfies then don't perform further conditional checks. At this point else
if statement is what you need.

Syntax

if(condition)

statements

else if(condition)

statements

else

statements

When every condition fails then final else statement is executed.

Example

<script>

VAPM,Almala Page 22
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

var a=3;

var b=4;

if(a > b)

document.write("a is greater than b");

else if(a < b)

document.write("a is smaller than b");

else

document.write("Nothing worked");

</script>

switch statement
switch statements do the same task that else if statements do. But use switch statements when
conditions are more. In that case, switch statements perform better than else if statements.

Syntax

switch(expression)

VAPM,Almala Page 23
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

case value-1: statements; break;

case value-2: statements; break;

case value-3: statements; break;

............

case value-n: statements; break;

default: statements; break;

switch evaluates the expression and checks whether it matches with any case. If it matches with
any case then statements within that case construct are executed followed by break statement.
break statement makes sure that no more case statement gets executed. In case if the expression
doesn't match any case value then default case is executed.

There could be any number of statements. No curly braces is needed inside case construct. Also
you can omit the break statement in the default construct if default is the last statement within
switch.

Example

<script>

var a = 7;

VAPM,Almala Page 24
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

switch(a)

case 1: document.write("one"); break;

case 2: document.write("two"); break;

case 3: document.write("three"); break;

case 4: document.write("four"); break;

case 5: document.write("five"); break;

default: document.write("number not found");

//outputs three

</script>

Note: Check that I have dropped the break statement for the default case construct. It will work
fine but try to put the default statement above case 1 and see the result. Also try this program
removing all the break statements.

case value can be any number, character or string. Keep this in mind.

Example

<script>

var i = 'h';

switch(i)

VAPM,Almala Page 25
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

case 'a': document.write("a found"); break;

case 'b': document.write("b found"); break;

case 'c': document.write("c found"); break;

case 'h': document.write("h found"); break;

case 'string': document.write("string found"); break;

default: document.write("nothing found");

//outputs h found

</script>

Ternary Operator (?:)


Ternary operator is preferred by many programmers. It contains 3 operands that's why the name
ternary operator.

Syntax

condition ? if-true-execute-this : if-false-execute-this;

If condition goes right then statement before colon is executed and if false then statement after
colon is executed. Multiple statements are not allowed. But you can execute multiple statements
by making a function and calling the function if the condition goes true or false accordingly.

Example

<script>

true ? document.write("True value found") : document.write("False value found");

document.write("<br />");

//outputs True value found

VAPM,Almala Page 26
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

(5>4 && 4===3) ? document.write("True") : document.write("False");

document.write("<br />");

//outputs False

var a = (true) ? 1 : 2;

document.write(a);

//outputs 1

</script>

Nested if else or switch statements


You can insert if or else or switch condition within another if or else or switch condition. This is
called nesting. You can nest if, else or switch conditions up to any number of level but doing so
will make you code more confusing. So use it wisely.

Syntax

if(condition)

if(other condition)

statements;

VAPM,Almala Page 27
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

else

if(other condition)

statements;

else

switch(expression)

case value-1: statements; break;

......

Type Casting in JavaScript

Converting a data type into another is known as type casting. Sometimes there is a need to
convert the data type of one value to another.

typeof
typeof operator is used to return the data type of an operand.

Syntax

VAPM,Almala Page 28
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

typeof operand;

Example

<script>

var a;

document.write(typeof a); //outputs undefined

document.write("<br />");

document.write(typeof "SyntaxPage"); //outputs string

document.write("<br />");

document.write(typeof 7); //outputs number

document.write("<br />");

document.write(typeof true); //outputs boolean

document.write("<br />");

document.write(typeof document); //outputs object

document.write("<br />");

document.write(typeof document.write); //outputs function

VAPM,Almala Page 29
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

document.write("<br />");

</script>

The code is self explanatory. The variable a has not been initialized that's why its type is
showing as undefined. Try to assign some value to it and see the result.

Converting to Boolean
To convert a value to boolean data type, just pass the value to Boolean function.

Syntax

Boolean(value);

Example

<script>

var b = 1;

b = Boolean(b);

document.write(b + " : " + typeof b); //outputs true : boolean

</script>

Converting to String
To convert a value to string data type, just pass the value to String function.

Syntax

VAPM,Almala Page 30
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

String(value);

Example

<script>

var s = 1;

s= String(s);

document.write(s + " : " + typeof s); //outputs 1 : string

</script>

Converting to Number
Many times string needs to get converted into numbers. To convert a value to number data type,
just pass the value to Number function.

Syntax

Number(value);

Example

<script>

var n1 = true;

var n2 = "1str";

VAPM,Almala Page 31
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

var n3 = "123";

n1 = Number(n1);

n2 = Number(n2);

n3 = Number(n3);

document.write(n1 + " : " + typeof n1); //outputs 1 : number

document.write("<br />");

document.write(n2 + " : " + typeof n2); //outputs NaN : number

document.write("<br />");

document.write(n3 + " : " + typeof n3); //outputs 123 : number

document.write("<br />");

</script>

true is represented as 1 in numeric so n1 after conversion stores value 1.


"1str" after conversion doesn't represent a valid number that's why the output is NaN. NaN
means not a number. Its a language construct.
"123" after conversion represents valid number 123.

There are other methods to convert string to number format.

parseInt
parseInt() function is used to convert strings values into numbers. It works differently than
Number() function. It doesn't work for boolean or other data-types values. For others values or

VAPM,Almala Page 32
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

string that doen't contain numbers in it, parseInt() will just output NaN. Examples will clear this
idea.

Syntax

parseInt(string);

Example

<script>

var n1 = true;

var n2 = "1str";

var n3 = "123";

var n4 = "str123str1";

n1 = parseInt(n1);

n2 = parseInt(n2);

n3 = parseInt(n3);

n4 = parseInt(n4);

document.write(n1 + " : " + typeof n1); //outputs NaN : number

document.write("<br />");

document.write(n2 + " : " + typeof n2); //outputs 1: number

document.write("<br />");

VAPM,Almala Page 33
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

document.write(n3 + " : " + typeof n3); //outputs 123 : number

document.write("<br />");

document.write(n3 + " : " + typeof n4); //outputs 123 : number

document.write("<br />");

</script>

parseFloat
parseFloat() function is used to convert strings values into floating point numbers. It works
similar to parseInt() function with an exception of handling decimal point numbers. For example,
1.23 is represented as 123e-2. parseInt("123e-2") will result in 123 but parseFloat("123e-2") will
give 1.23.

Syntax

parseFloat(string);

Example

<script>

var n1 = "123e-2";

var n2 = "1str";

var n3 = "123";

var n4 = "str123str1";

VAPM,Almala Page 34
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

n1 = parseFloat(n1);

n2 = parseFloat(n2);

n3 = parseFloat(n3);

n4 = parseFloat(n4);

document.write(n1 + " : " + typeof n1); //outputs 1.23 : number

document.write("<br />");

document.write(n2 + " : " + typeof n2); //outputs 1: number

document.write("<br />");

document.write(n3 + " : " + typeof n3); //outputs 123 : number

document.write("<br />");

document.write(n3 + " : " + typeof n4); //outputs 123 : number

document.write("<br />");

</script>

Loops in JavaScript

Loops are used to execute a specific statement for a given number of times. Loops are always
followed by some condition. JavaScript provides all the basic loops that other programming
languages have.

VAPM,Almala Page 35
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

while loop
while loop checks for a given condition to be true to execute statements that it contains within it.
When the condition becomes false, while loop break the execution of statements.

Syntax

initializer;

while(condition)

statement-1;

statement-2;

.....

modifier;

initializer is a variable that is tested within the condition. modifier modifies the initializer so that
the condition becomes false at some point.

Note: Make sure that your condition goes false somehow else you will be in an infinite loop.

Example

<script>

var i = 0;

while(i<6)

document.write(i);

document.write("<br />");

i++;

VAPM,Almala Page 36
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

</script>

do while loop
do while loop first execute the statements that it contain and then check for a condition. So even
if the condition is false do-while loop is going to run at least once.

Syntax

initializer;

do

statement-1;

statement-2;

.....

modifier;

while(condition);

Example

<script>

var i = 5;

do

VAPM,Almala Page 37
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

document.write(i);

document.write("<br />");

i++;

while(i<6);

</script>

for loop
for loop is generally used when the number of iterations/repetitions are already known. Its not
that such tasks can't be done by while loop but its just a matter of preference.

Syntax

for(initializer; condition; modifier)

statement-1;

.....

Here, initializer is a variable that is defined once in the beginning of a for loop. It is optional and can be
ignored. condition is checked after initialization. Then statements are executed and finally modifier
modifies the initializer. After that again condition is checked and the process continues. Modifier can also
be ignored.

Note: The only required thing within for loop is condition.

You can drop the curly braces if only one statement is within the for loop.

Syntax

VAPM,Almala Page 38
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

<script>

for(var i=0;i<10;i++)

document.write(i);

document.write("<br />");

</script>

Nested Loops
Any loop can be inserted inside any other loop. This is called nesting. for loop can be nested
inside while or for loop. Similarly while loop can be nested inside for loop or another while loop.

Syntax

for(initializer; condition; modifier)

while(condition)

statements;

Example

<script>

VAPM,Almala Page 39
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

var i,j;

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

document.write("Outer Loop : " + i);

document.write("<br />");

for(j=0;j<3;j++)

document.write("Inner Loop : " + j);

document.write("<br />");

document.write("<br />");

/*************output***************

Outer Loop : 0

Inner Loop : 0

Inner Loop : 1

Inner Loop : 2

VAPM,Almala Page 40
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

Outer Loop : 1

Inner Loop : 0

Inner Loop : 1

Inner Loop : 2

Outer Loop : 2

Inner Loop : 0

Inner Loop : 1

Inner Loop : 2

***********************************/

</script>

Can you guess how above loop works? First outer for loop initializes i, checks for the condition
then executes its first two statements. After that inner for loop starts to work. After executing its
statements 3 times, outer for loop is given the control again. And the process is repeated.

Loops Control Statements in JavaScript

Loop control statements deviates a loop from its normal flow. All the loop control statements are
attached to some condition inside the loop.

break statement
break statement is used to break the loop on some condition.

Syntax

for(initializer, condition, modifier)

if(condition)

VAPM,Almala Page 41
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

break;

statements;

//same thing is valid for while loop

while(condition)

if(condition)

break;

statements;

Example

<script>

for(var i=1;i<10;i++)

if(i===7) break;

VAPM,Almala Page 42
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

document.write(i + "<br />");

/**********output***********

***************************/

</script>

for loop should print from 1 - 10. But inside loop we have given a condition that if value of i
equals to 7, then break out of loop. I have left the curly braces within the if condition because
there is only one statement to be executed.

Remember break burst the nearest for loop within which it is contained. To understand what
it means check out the next example.

Example

<script>

for(var i=1;i<=3;i++)

document.write("Outer Loop : " + i + "<br />");

VAPM,Almala Page 43
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

for(var j=1;j<=3;j++)

document.write("Inner Loop : " + j + "<br />");

if(j===2)

break;

document.write("<br />");

/**********output***********

Outer Loop : 1

Inner Loop : 1

Inner Loop : 2

Outer Loop : 2

Inner Loop : 1

Inner Loop : 2

VAPM,Almala Page 44
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

Outer Loop : 3

Inner Loop : 1

Inner Loop : 2

***************************/

</script>

continue statement
continue statement is used to skip an iteration of a loop.

Syntax

for(initializer, condition, modifier)

if(condition)

continue;

statements;

//same thing is valid for while loop

while(condition)

if(condition)

VAPM,Almala Page 45
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

continue;

statements;

Example

<script>

for(var i=0;i<10;i++)

if(i===3 || i===7) continue;

document.write(i + "<br />");

/**********output***********

VAPM,Almala Page 46
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

***************************/

</script>

In the code above when the value of i becomes 3 or 7, continue forces the loop to skip without
further executing any instructions inside the for loop in that current iteration.

Remember continue skips the nearest loop iteration within which it is contained. To
understand what it means check out the next example.

Example

<script>

for(var i=1;i<=3;i++)

document.write("Outer Loop : " + i + "<br />");

for(var j=1;j<=3;j++)

if(j===2)

continue;

document.write("Inner Loop : " + j + "<br />");

VAPM,Almala Page 47
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

document.write("<br />");

/**********output***********

Outer Loop : 1

Inner Loop : 1

Inner Loop : 3

Outer Loop : 2

Inner Loop : 1

Inner Loop : 3

Outer Loop : 3

Inner Loop : 1

Inner Loop : 3

***************************/

</script>

When value of j inside inner loop becomes 2, it skips that iteration.

Mathematical Constants in JavaScript


Math object in JavaScript provides various mathematical constants and mathematical functions.
Below is the list of various constants.

VAPM,Almala Page 48
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

Constant Description Value

Math.PI Constant PI 3.141592653589793

Math.E Euler's Constant 2.718281828459045

Math.LN2 Natural log of 2 0.6931471805599453

Math.LN10 Natural log of 10 2.302585092994046

Math.LOG2E Base 2 log of E 1.4426950408889634

Math.LOG10E Base 10 log of E 0.4342944819032518

Math.SQRT1_2 Square root of 0.5 0.7071067811865476

Math.SQRT2 Squre root of 2 1.4142135623730951

Example

<script>

var x = Math.PI;

document.write(x); //outputs 3.141592653589793

</script>

Commonly used Mathematical Methods in JavaScript


Some commonly used methods that are used mostly in JavaScript are as follows:

VAPM,Almala Page 49
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

Method Description

Math.abs(number) returns an absolute value

Math.sqrt(number) returns square root of a number

Math.pow(a, b) returns power value a raised to the power b

Math.log(number) returns natural log value

Math.exp(number) returns Euler's contsant raised to power of specified number

Math.max(a, b) returns larger of two numbers

Math.min(a, b) returns smaller of two numbers

Example

<script>

var a = Math.abs(-7); //7

document.write(a);

document.write("<br />");

a = Math.sqrt(64); //8

document.write(a);

document.write("<br />");

VAPM,Almala Page 50
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

a = Math.pow(2, 3); //2x2x2 = 8

document.write(a);

document.write("<br />");

a = Math.log(20); //2.995732273553991

document.write(a);

document.write("<br />");

a = Math.exp(5); //148.41315910257657

document.write(a);

document.write("<br />");

a = Math.max(5,10); //10

document.write(a);

document.write("<br />");

a = Math.min(5,10); //5

document.write(a);

document.write("<br />");

a = Math.min(-50,-49); //-50

VAPM,Almala Page 51
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

document.write(a);

</script>

Trigonometric Methods in JavaScript


Trignometric Methods are rarely used but still sometimes helpful. Some of the trigonometric
methods used are given below:

Method Description

Math.sin(number) returns sine value

Math.cos(number) returns cosine value

Math.tan(number) returns tangent value

Math.asin(number) returns arc sine value

Math.acos(number) returns arc cosine value

Math.atan(number) returns arc tangent value

Example

<script>

var a = Math.sin(0); //sin 0 degree = 0

document.write(a);

document.write("<br />");

VAPM,Almala Page 52
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

a = Math.cos(0); //cos 0 degree = 1

document.write(a);

document.write("<br />");

a = Math.tan(0); //tan 0 degree = 0

document.write(a);

</script>

Rounding Numbers in JavaScript


You can round off numbers using the functions given in the table.

Method Description

Math.ceil(number) returns rounded up integer value

Math.floor(number) returns rounded down integer value

Math.round(number) returns nearest integer value

Example

<script>

var a = Math.ceil(12.4); //13

document.write(a);

document.write("<br />");

VAPM,Almala Page 53
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

a = Math.floor(12.4); //12

document.write(a);

document.write("<br />");

a = Math.round(12.4); //12

document.write(a);

document.write("<br />");

a = Math.round(12.5); //13

document.write(a);

</script>

Rounding Number up to specific level of precision in JavaScript


While rounding a number using round() method, you will always end up getting some integer.
Not all the time you want this. Sometimes you need to get a value up to some specific decimal
level or precision. For example, Math.PI returns 3.141592653589793. What if you want to get
this value up to 2 decimal places (3.14)? For doing so, you can multiply the floating point
number with 100. Then use the round() method and then divide the number again by 100. Below
is a formula that you can use.

Syntax

(Math.round(number * precision factor)) / precision factor

Precision factor represents the decimal level and is equal to 10 raise to the power of the decimal
places. For example if you want 2 decimal places, precision factor will be 100(10^2), for 3
decimal places it should be 1000(10^3).

VAPM,Almala Page 54
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

Example

<script>

var p = Math.round(Math.PI); //3

document.write(p);

document.write("<br />");

//for 2 decimal places

var p = Math.PI * 100;

p = Math.round(p);

p /= 100;

document.write(p);

document.write("<br />");

//for 4 decimal places

var p = (Math.round(Math.PI * 10000))/10000;

document.write(p);

</script>

Random Number in JavaScript


Math.random() method is used to generate a random floating point number between 0.0 and
1.0. You can always increase its range by multiplying it to a number. For example, multiplying it

VAPM,Almala Page 55
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

with 10 will increase its range from 0.0 to 10.0. And to get an integer range, use Math.ceil() so
that the range actually becomes 1 to 10. You can use Math.floor() to make the range between 0
and 9.

Syntax

Math.random();

Example

<script>

var r = Math.random();

r *= 10;

r = Math.ceil(r); //returns any number between 1-10

document.write(r);

document.write("<br />");

r = Math.floor(Math.random()*10); //returns any number between 0-9

document.write(r);

</script>

Infinity in JavaScript
Infinity is a global property (variable) that is used to represent infinite values in JavaScript.

Example

<script>

VAPM,Almala Page 56
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

var i = 100 / 0;

document.write(i); //Infinity

</script>

There are also two other global properties in JavaScript, POSITIVE_INFINITY and
NEGATIVE_INFINITY but they are rarely used.

NaN in JavaScript
NaN is a global property which means "Not a Number".

Example

<script>

var n = "string" * 10; //NaN

document.write(n);

</script>

Working with Strings in JavaScript

String plays an important role in every programming languages. JavaScript is no exception. Also
every character in JavaScript is represented by some number. That numerical unicode is known
as charcode of that character. Example, 'A' is represented by 65.

Here are few functions that can be useful to help you out with your day to day coding work.

String Concatenation

VAPM,Almala Page 57
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

String concatenation refers to combining one string to another. Simplest way to join strings is
using '+' (plus) operator. But there is also a method concat() which can be used to unite strings
together.

Syntax

//using concat method

string1.concat(string2, string3, ...);

//using + operator

string1 + string2 + string3

Example

<script>

var str = "Syntax";

str = str.concat("Page"); //SyntaxPage

document.write(str);

document.write("<br />");

str = "JavaScript";

str = str.concat(" is", " fun", "<br />");

document.write(str); //JavaScript is fun

str = "JavaScript " + "is " + "awesome" + "<br />";

VAPM,Almala Page 58
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

document.write(str); //JavaScript is awesome

</script>

Splitting Strings
Various methods are available in JavaScript to get whole or some part of strings. Few commonly
used methods are as follows:

substring() method
substring method is used to get arbitrary string values between the index positions passed to it as
parameters.

Syntax

string.substring(start,[end])

First parameter specifies from where to copy the string. Second optional parameter specifies till
where to copy. Also, character specified by second parameter is not included. If second
parameter is not given then whole string after start position will be copied.

Example

<script>

var str = 'SyntaxPage';

var sub = str.substring(6); //Page

document.write(sub);

document.write("<br />)

str = 'JavaScript';

VAPM,Almala Page 59
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

sub = str.substring(4,7); //Src

document.write(sub);

//element at 4th position is excluded

</script>

substr() method
substr method is somewhat similar to substring() method with just one difference. The second
parameter in the substr() method specifies the length of the string to be copied, not the end
position.

Syntax

string.substr(start,length)

Example

<script>

var str = 'SyntaxPage';

var sub = str.substr(6); //Page

document.write(sub);

document.write("<br />")

str = 'JavaScript';

sub = str.substr(4,3); //Scr

VAPM,Almala Page 60
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

document.write(sub);

</script>

slice() method
slice method is used to get characters from a string between specified indexes passed to it as
parameters.

Syntax

string.slice(start, [end])

The element at the 'end' index is not included. If end index is not specified then the result will be
from start index till the end of the string.

Example

<script>

var str = "12345";

var sub = str.slice(1, 4); //234

document.write(sub);

document.write("<br />");

sub = str.slice(1); //2345

document.write(sub);

VAPM,Almala Page 61
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

</script>

split() method
split() method breaks a string into an array of string. It splits the string from the separator string
boundaries that is passed to it as parameter.

Syntax

string.split(separator,[size])

If no separator string is given then it will break the string into an array having just one element
which is string itself.

If optional size parameter is given then array formed will be of given size parameter ignoring the
rest of the characters.

Example

<script>

var str = "JavaScript is fun";

var sub = str.split(" ");

document.write(sub); //JavaScript,is,fun

document.write("<br />");

sub = str.split(" ", 1);

document.write(sub); //JavaScript

document.write("<br />");

VAPM,Almala Page 62
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

sub = str.split();

document.write(sub[0]); //JavaScript is fun

</script>

Changing Case
toLowerCase() method
toLowerCase() method is used to change the case of the string to lower case.

Syntax

string.toLowerCase()

Example

<script>

var str = "JavaScript is Awesome";

var lcase = str.toLowerCase();

document.write(lcase);

</script>

toUpperCase() method
toUpperCase() method is used to change the case of the string to upper case.

Syntax

VAPM,Almala Page 63
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

string.toUpperCase()

Example

<script>

var str = "JavaScript is Awesome";

var ucase = str.toUpperCase();

document.write(ucase);

</script>

Finding Characters
indexOf() method
indexOf() method is used to search for a given substring in the parent string and returns substring
position.

Syntax

string.indexOf(needle,[fromIndex])

Optional second parameter decides from where to begin searching the string. It starts searching
from the beginning if optional second parameter is not given. In case needle(substring) is not
found then it returns -1.

Example

<script>

var str = "JavaScript is an Awesome Script";

VAPM,Almala Page 64
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

var pos = str.indexOf("Script"); //4

document.write(pos);

document.write("<br />");

var pos = str.indexOf("Script",5); //25

document.write(pos);

</script>

lastIndexOf() method
lastIndexOf() method is used to search for a given substring beginning the search from the end. It
returns needle's position. In case needle(substring) is not found then it returns -1.

Syntax

string.lastIndexOf(needle,[fromIndex])

It starts searching from the end if optional second parameter is not given. In case
needle(substring) is not found then it returns -1.

Example

<script>

var str = "JavaScript is an Awesome Script";

var pos = str.lastIndexOf("Script"); //25

document.write(pos);

VAPM,Almala Page 65
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

var pos = str.lastIndexOf("Script",24); //4

document.write(pos);

</script>

search() method
search() returns the index position of the needle if found else it returns -1. It looks somewhat
similar to indexOf() method but seach() method works with regular expressions. Regular
expressions will be discussed later.

Syntax

string.search(regexp)

Example

<script>

var str = "JavaScript is an Awesome Script";

var pos = str.search("Script"); //4

document.write(pos);

</script>

match() method

VAPM,Almala Page 66
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

match() returns the substring(needle) if found in the main string else it returns null. match()
method also works with regular expressions. Performance wise indexOf() method is faster than
match() and search().

Syntax

string.match(regexp)

Example

<script>

var str = "JavaScript is an Awesome Script";

var pos = str.match("Script"); //Script

document.write(pos);

</script>

charAt() method
charAt() returns the character at a particular index which is passed to it as an argument.

string.charAt(index)

Example

<script>

var str = "JavaScript is an Awesome Script";

var c = str.charAt(4); //S

VAPM,Almala Page 67
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

document.write(c);

</script>

charCodeAt() method
charCodeAt() returns the unicode numeric value of a character at a particular index which is
passed to it as an argument.

string.charAt(index)

Example

<script>

var str = "JavaScript is an Awesome Script";

var u = str.charCodeAt(4); //83

document.write(u);

</script>

Replacing word in a string


replace() method
replace() method is used to find and replace some or all occurrence of a string/character with
some new specified string/character within a string. To replace more than one value within a
string pass regular expression as first argument.

Syntax

VAPM,Almala Page 68
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

string.replace(regular_expression/string, 'new_string')

Example

<script>

var str = "JavaScript is Awesome";

var newStr = str.replace("Awesome", "Amazing");

document.write(newStr);

</script>

Summary of String Methods in JavaScript

Method Description

str.concat(str1, str2,...) combines one or more string

returns substring from start to end unless end index position


str.substring(start,[end])
is specified

returns substring from start to end unless number of


str.substr(start,len)
characters(length) is specified

str.slice(start, [end]) returns substring between specified indexes

breaks a string into an array from the separator string


str.split(sep,[size])
boundaries

str.toLowerCase() returns lowercase string

VAPM,Almala Page 69
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

str.toUpperCase() returns uppercase string

returns character present at specified index beginning the


str.indexOf(needle,[fromIndex]) search from start. Second parameter decides from where to
begin search

returns character present at specified index beginning the


str.lastIndexOf(needle,[fromIndex]) search from end. Second parameter decides from where to
begin search

returns the index position of the substring if found else it


str.search(regexp)
returns -1

str.match(regexp) returns the substring if found else it returns null.

returns the character at a particular index which is passed to


str.charAt(index)
it as an argument

returns the unicode numeric value of a character at a


str.charCodeAt(index)
particular index which is passed to it as an argument

str.replace(regular_expression/string, returns string after replacing some or all occurrence of old


"new_string") string with new string within a given string.

Date and Time in JavaScript

Date object in JavaScript can be used to get date and time. Date object has various methods to
exploit date and time. To get date and time use new keyword followed by with Date object
constructor.

Syntax

//get date and time

new Date();

VAPM,Almala Page 70
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

//set date and time

new Date(year, month, date, hours, minutes, seconds, milliseconds);

Example

<script>

var now = new Date();

document.write(now);

//Fri Feb 20 2015 21:12:09 GMT+0530 (India Standard Time)

document.write('<br />');

now = new Date(2005, 11, 21, 12, 30, 30, 0);

document.write(now);

//Wed Dec 21 2005 12:30:30 GMT+0530 (India Standard Time)

</script>

Working with Date


To get and set date, Date objects has various methods.

date.getDay() returns the day number (0-6, 0 for sun, 1 for mon and so on)

VAPM,Almala Page 71
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

date.getDate() returns the date (1 to 31)

date.getMonth() returns the month (0-11, 0 for jan and so on)

date.getFullYear() returns 4 digit year

date.setDate(value) sets the date (1 to 31)

date.setMonth(value) sets the month (0-11, 0 for jan and so on)

date.setFullYear() sets 4 digit year

Example

<script>

var days = ['Sun', 'Mon', 'Tues', 'Wed', 'Thu', 'Fri', 'Sat'];

var months = ['Jan', 'Feb', 'March', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

var d = new Date();

var day = d.getDay();

day = days[day];

var date = d.getDate();

VAPM,Almala Page 72
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

var month = d.getMonth();

month = months[month];

var year = d.getFullYear();

document.write(day + " " + date + " " + month + " " + year);

</script>

Working with Time


To get and set time, Date objects has various methods.

date.getHours() returns hour in 24-hour format (0-23)

date.getMinutes() returns minute (0-59)

date.getSeconds() returns second (0-59)

date.getMilliseconds() returns millisecond (0-999)

date.setHours() sets hour in 24-hour format (0-23)

date.setMinutes() sets minute (0-59)

date.setSeconds() sets second (0-59)

date.setMilliseconds() sets millisecond (0-999)

Example

VAPM,Almala Page 73
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

<script>

var t = new Date();

var hour = t.getHours();

var min = t.getMinutes();

var sec = t.getSeconds();

var milli = t.getMilliseconds();

document.write(hour + ":" + min + ":" + sec + ":" + milli);

</script>

Working with Strings in JavaScript

String plays an important role in every programming languages. JavaScript is no exception. Also
every character in JavaScript is represented by some number. That numerical unicode is known
as charcode of that character. Example, 'A' is represented by 65.

Here are few functions that can be useful to help you out with your day to day coding work.

String Concatenation

VAPM,Almala Page 74
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

String concatenation refers to combining one string to another. Simplest way to join strings is
using '+' (plus) operator. But there is also a method concat() which can be used to unite strings
together.

Syntax

//using concat method

string1.concat(string2, string3, ...);

//using + operator

string1 + string2 + string3

Example

<script>

var str = "Syntax";

str = str.concat("Page"); //SyntaxPage

document.write(str);

document.write("<br />");

str = "JavaScript";

str = str.concat(" is", " fun", "<br />");

document.write(str); //JavaScript is fun

str = "JavaScript " + "is " + "awesome" + "<br />";

VAPM,Almala Page 75
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

document.write(str); //JavaScript is awesome

</script>

Splitting Strings
Various methods are available in JavaScript to get whole or some part of strings. Few commonly
used methods are as follows:

substring() method
substring method is used to get arbitrary string values between the index positions passed to it as
parameters.

Syntax

string.substring(start,[end])

First parameter specifies from where to copy the string. Second optional parameter specifies till
where to copy. Also, character specified by second parameter is not included. If second
parameter is not given then whole string after start position will be copied.

Example

<script>

var str = 'SyntaxPage';

var sub = str.substring(6); //Page

document.write(sub);

document.write("<br />)

str = 'JavaScript';

VAPM,Almala Page 76
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

sub = str.substring(4,7); //Src

document.write(sub);

//element at 4th position is excluded

</script>

substr() method
substr method is somewhat similar to substring() method with just one difference. The second
parameter in the substr() method specifies the length of the string to be copied, not the end
position.

Syntax

string.substr(start,length)

Example

<script>

var str = 'SyntaxPage';

var sub = str.substr(6); //Page

document.write(sub);

document.write("<br />")

str = 'JavaScript';

sub = str.substr(4,3); //Scr

VAPM,Almala Page 77
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

document.write(sub);

</script>

slice() method
slice method is used to get characters from a string between specified indexes passed to it as
parameters.

Syntax

string.slice(start, [end])

The element at the 'end' index is not included. If end index is not specified then the result will be
from start index till the end of the string.

Example

<script>

var str = "12345";

var sub = str.slice(1, 4); //234

document.write(sub);

document.write("<br />");

sub = str.slice(1); //2345

document.write(sub);

VAPM,Almala Page 78
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

</script>

split() method
split() method breaks a string into an array of string. It splits the string from the separator string
boundaries that is passed to it as parameter.

Syntax

string.split(separator,[size])

If no separator string is given then it will break the string into an array having just one element
which is string itself.

If optional size parameter is given then array formed will be of given size parameter ignoring the
rest of the characters.

Example

<script>

var str = "JavaScript is fun";

var sub = str.split(" ");

document.write(sub); //JavaScript,is,fun

document.write("<br />");

sub = str.split(" ", 1);

document.write(sub); //JavaScript

document.write("<br />");

VAPM,Almala Page 79
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

sub = str.split();

document.write(sub[0]); //JavaScript is fun

</script>

Changing Case
toLowerCase() method
toLowerCase() method is used to change the case of the string to lower case.

Syntax

string.toLowerCase()

Example

<script>

var str = "JavaScript is Awesome";

var lcase = str.toLowerCase();

document.write(lcase);

</script>

toUpperCase() method
toUpperCase() method is used to change the case of the string to upper case.

Syntax

VAPM,Almala Page 80
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

string.toUpperCase()

Example

<script>

var str = "JavaScript is Awesome";

var ucase = str.toUpperCase();

document.write(ucase);

</script>

Finding Characters
indexOf() method
indexOf() method is used to search for a given substring in the parent string and returns substring
position.

Syntax

string.indexOf(needle,[fromIndex])

Optional second parameter decides from where to begin searching the string. It starts searching
from the beginning if optional second parameter is not given. In case needle(substring) is not
found then it returns -1.

Example

<script>

var str = "JavaScript is an Awesome Script";

VAPM,Almala Page 81
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

var pos = str.indexOf("Script"); //4

document.write(pos);

document.write("<br />");

var pos = str.indexOf("Script",5); //25

document.write(pos);

</script>

lastIndexOf() method
lastIndexOf() method is used to search for a given substring beginning the search from the end. It
returns needle's position. In case needle(substring) is not found then it returns -1.

Syntax

string.lastIndexOf(needle,[fromIndex])

It starts searching from the end if optional second parameter is not given. In case
needle(substring) is not found then it returns -1.

Example

<script>

var str = "JavaScript is an Awesome Script";

var pos = str.lastIndexOf("Script"); //25

document.write(pos);

VAPM,Almala Page 82
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

var pos = str.lastIndexOf("Script",24); //4

document.write(pos);

</script>

search() method
search() returns the index position of the needle if found else it returns -1. It looks somewhat
similar to indexOf() method but seach() method works with regular expressions. Regular
expressions will be discussed later.

Syntax

string.search(regexp)

Example

<script>

var str = "JavaScript is an Awesome Script";

var pos = str.search("Script"); //4

document.write(pos);

</script>

match() method

VAPM,Almala Page 83
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

match() returns the substring(needle) if found in the main string else it returns null. match()
method also works with regular expressions. Performance wise indexOf() method is faster than
match() and search().

Syntax

string.match(regexp)

Example

<script>

var str = "JavaScript is an Awesome Script";

var pos = str.match("Script"); //Script

document.write(pos);

</script>

charAt() method
charAt() returns the character at a particular index which is passed to it as an argument.

string.charAt(index)

Example

<script>

var str = "JavaScript is an Awesome Script";

var c = str.charAt(4); //S

VAPM,Almala Page 84
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

document.write(c);

</script>

charCodeAt() method
charCodeAt() returns the unicode numeric value of a character at a particular index which is
passed to it as an argument.

string.charAt(index)

Example

<script>

var str = "JavaScript is an Awesome Script";

var u = str.charCodeAt(4); //83

document.write(u);

</script>

Replacing word in a string


replace() method
replace() method is used to find and replace some or all occurrence of a string/character with
some new specified string/character within a string. To replace more than one value within a
string pass regular expression as first argument.

Syntax

VAPM,Almala Page 85
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

string.replace(regular_expression/string, 'new_string')

Example

<script>

var str = "JavaScript is Awesome";

var newStr = str.replace("Awesome", "Amazing");

document.write(newStr);

</script>

Summary of String Methods in JavaScript

Method Description

str.concat(str1, str2,...) combines one or more string

returns substring from start to end unless end index position


str.substring(start,[end])
is specified

returns substring from start to end unless number of


str.substr(start,len)
characters(length) is specified

str.slice(start, [end]) returns substring between specified indexes

breaks a string into an array from the separator string


str.split(sep,[size])
boundaries

str.toLowerCase() returns lowercase string

VAPM,Almala Page 86
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

str.toUpperCase() returns uppercase string

returns character present at specified index beginning the


str.indexOf(needle,[fromIndex]) search from start. Second parameter decides from where to
begin search

returns character present at specified index beginning the


str.lastIndexOf(needle,[fromIndex]) search from end. Second parameter decides from where to
begin search

returns the index position of the substring if found else it


str.search(regexp)
returns -1

str.match(regexp) returns the substring if found else it returns null.

returns the character at a particular index which is passed to


str.charAt(index)
it as an argument

returns the unicode numeric value of a character at a


str.charCodeAt(index)
particular index which is passed to it as an argument

str.replace(regular_expression/string, returns string after replacing some or all occurrence of old


"new_string") string with new string within a given string.

Different Types of Conditional Statements


There are mainly three types of conditional statements in JavaScript.

1. If statement
2. If…Else statement
3. If…Else If…Else statement

If statement
Syntax:

if (condition)

VAPM,Almala Page 87
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

lines of code to be executed if condition is true

You can use If statement if you want to check only a specific condition.

Try this yourself:


This code is editable. Click Run to Execute

<html>

<head>

<title>IF Statments!!!</title>

<script type="text/javascript">

var age = prompt("Please enter your age");

if(age>=18)

document.write("You are an adult <br />");

if(age<18)

document.write("You are NOT an adult <br />");

</script>

</head>

<body>

</body>

VAPM,Almala Page 88
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]

</html>

VAPM,Almala Page 89
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Introduction

JavaScript Cookies are a great way to save a user's preferences in his / her browser. This is useful
for websites and users both, if not used to steal privacy.

What are cookies?

A cookie is a small piece of text stored on the visitor's computer by a web browser. As the
information is stored on the hard drive it can be accessed later, even after the computer is turned
off.

A cookie can be used for authenticating, session tracking, remember specific information about
the user like his name, password, last visited date etc.

As cookies as a simple piece of text they are not executable. In javaScript, we can create and
retrieve cookie data with JavaScript's document object's cookie property.

What cookies cannot do ?

 The first is that all modern browser support cookies, but the user can disable them. In IE,
go to Tools and select Internet options, a window will come. Click on privacy and select
advanced button, another new window will come, from here you can disable cookie.

 Cookies can identify the computer being used, not the individual.

 The most modern browser is expected to be able to store at least 300 cookies of four
kilobytes (4 kb) per server or domain.

 For each domain and path, you can store upto 20 cookies.

 Cookies cannot access by any other computer except the visitor's computer that created
the cookie.

 A website can set and read only its own cookies (for example, Yahoo can’t read IE's
cookies).

JavaScript: Setting Cookies


[VAPM,Almala-Inst.Code-1095
]1 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

cookies.txt :

During the browsing session browser stores the cookies in memory, at the time of quitting they
goto the file called cookies.txt. Different browser store cookies files in a different location in the
disk.

For example on windows 2000 firefox stores the cookies into C:\Documents and
Settings\your_login_name_here\LocalSettings\ApplicationData\Mozilla\Firefox\Profiles\default
.7g1\Cache. Note that the "default.7g1" folder name may vary depending on the version of
Firefox you have Everytime When you open your browser, your cookies are read from the stored
location and at the closing, your browser, cookies are reserved to disk. As a cookie expires it is
no longer saved to the hard drive.

There are six parts of a cookie : name, value, expires, path, domain, and security. The first two
parts i.e. name and value are required and rest parts are optional.

Syntax

document.cookie="NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN; secure";


The different components of the above syntax are discussed with a heading specifying the
component.

name and value

The first part of the cookie string must have the name and value. The entire name/value must be
a single string with no commas, semicolons or whitespace characters. Here is an example which
stores the string "George" to a cookie named 'myName". The JavaScript statement is :

document.cookie = "myName=George";

Using encodeURIComponent() and decodeURIComponent() function.

Using encodeURIComponent() function it is ensured that the cookie value string does not
contain any commas, semicolons, or whitespace characters. which are not allowed in cookie
values.

encodeURIComponent("Good Morning");

Returns the string as :

[VAPM,Almala-Inst.Code-1095
]2 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Good%20Morning

while decodeURIComponent("Good%20Morning") decode the string as :

Good Morning.

expires

The cookie has a very limited lifespan. It will disappear when a user exits the browser. To give
more life to the cookies you must set an expiration date in the following format.

DD-Mon-YY HH:MM:SS GMT

Here is an example where the cookie will live upto Mon, 12 Jun 2011:00:00:00 GMT

document.cookie = "VisiterName=George; expires=Mon, 12 Jun 2011:00:00:00 GMT; ";

In the above example we have written the date in the pages, but in real life, you can use the Date
object to get the current date, and then set a cookie to expire six months or ten months.

Here is the example

cookieExpire = new Date();

cookieExpire.setMonth(cookieExpire.getMonth() + 10);

document.cookie = "VisitorName=George; expires="+ expireDate.toGMTString() + ";";

Copy

The above JavaScript code will create a new cookie called VisitorName with the value of
'George' and it will expire after 10 months from the current date.

path

If a page www.w3resource.com/javascript/ sets a cookie then all the pages in that directory (i.e.
../javascript) and its subdirectories will be able to read the cookie. But a page in
www.w3resource/php/ directory can not read the cookie. Usually, the path is set to root level

[VAPM,Almala-Inst.Code-1095
]3 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

directory ( '/' ) , which means the cookie is available for all the pages of your site. If you want the
cookie to be readable in a specific directory called php, add path=/php;.

Here is the example where we have set a specific path called 'php'

document.cookie= "VisiterName=George;expires=Mon,12Jun2011:00:00:00"

+ ";path=/php;";

Copy

In the following code here we have specified that the cookie is available to all subdirectories of
the domain.

document.cookie= "VisiterName=George;expires=Mon,12Jun2011:00:00:00"

+ ";path=/;";

Copy

domain

Some websites have lots of domains. The purpose of the 'domain' is to allow cookies to other
subdomains. For example a web portal call 'mysite'. It's main site is http://www.mysite.com with
a matrimonial site (http://matimonial.mysite.com), a financial site (http://financial.mysite.com)
and a travel site (http://travel.mysite.com). By default, if a web page on the travel site sets a
cookie, pages on the financial site cannot read that cookie. But if you add domain = mysite to a
cookie, all domain ending with 'mysite' can read the cookie. Note that the domain name must
contain at least two dots (.), e.g., ".mysite.com"

Here is the example.

document.cookie= "VisiterName=George;expires=Mon,12Jun2011:00:00:00"

+ ";path=/" + domain = mysite.com;";

[VAPM,Almala-Inst.Code-1095
]4 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Copy

Secure

The last part of the cookie string is the secure part which is a boolean value. The default value is
false. If the cookie is marked secure (i.e. secure value is true) then the cookie will be sent to web
server and try to retrieve it using a secure communication channel. This is applicable for those
servers which have SSL (Secure Sockets Layer) facility.

JavaScript: Creating Cookies

We have already learned the various parts of the cookie like name, value, expires, path, domain,
and security. Let's create a simple cookie.
In the following example, we have written a function name 'CookieSet' and set some of its
attributes.

Example:

In the following web document four parameters name, value, expires and path parts sent to the
function 'CookieSet'. The secure and domain parts are not essential here. Empty values set to
expires and path parts and there is a checking for expires and path parts. If expires receive empty
value it will set the expires date 9 months from the current date and if path receives empty value
then current directory and subdirectories will be the path. The toUTCString converts the date to a
string, using the universal time convention.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />

<title>JavaScript creating cookies - example1</title>

</head>

[VAPM,Almala-Inst.Code-1095
]5 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

<body>

<h1 style="color: red">JavaScript creating cookies - example1</h1>

<hr />

<script type="text/javascript">

//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[

function CookieSet (cName, cValue, cPath, cExpires)

cvalue = encodeURIComponent(cValue);

if (cExpires == "")

var cdate = new Date();

cdate.setMonth(cdate.getMonth() + 9);

cExpires = cdate.toUTCString();

if (cPath != "")

cPath = ";Path=" + cPath;

document.cookie = cName + "=" + cValue +"expires=" + cExpires + cPath;

CookieSet("Name","George ","","");

alert(document.cookie)

//]]>

</script>

</body>
[VAPM,Almala-Inst.Code-1095
]6 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

</html>

Copy

View the example in the browser

Example: Receive real data from the user and store it in a cookie.

The following web document receives real data from the user and stores it in a cookie for next
one year from the current date.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />

<title>JavaScript creating cookies - receive real data. example1</title>

</head>

<body>

<h1 style="color: red">JavaScript creating cookies, receive real data. - example1</h1>

<hr />

<script type="text/javascript">

//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[

var visitor_name = prompt("What's your name?","");

var expr_date = new Date("December 30, 2012");

var cookie_date = expr_date.toUTCString();

final_cookie = "Name =" + encodeURIComponent(visitor_name) + ";expires_on = " +


cookie_date;

document.cookie = final_cookie;

[VAPM,Almala-Inst.Code-1095
]7 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

alert(final_cookie);

//]]>

</script>

</body>

</html>

Copy

View the example in the browser

Delete a cookie

Deleting a cookie is extremely easy. To delete a cookie first accept the name of the cookie and
create a cookie with the same name and set expiry date one day ago from the current date. As the
expiry date has already passed the browser removes the cookie immediately. It is not confirmed
that the cookie has deleted during the current session, some browser maintains the cookie until
restart the browser. To see the example read A real example on Cookiespage.

JavaScript: Reading Cookies

When a browser opens a web page, the browser reads the cookies (provided it has already stored
it) that have stored on your machine. We used document.cookie to retrieve the information about
the cookie.

Example:

In the following web document, we receive a name from the visitor and stored it in the cookie
called "Name".

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

[VAPM,Almala-Inst.Code-1095
]8 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />

<title>JavaScript creating cookies - receive real data. example1</title>

</head>

<body>

<h1 style="color: red">JavaScript creating cookies, receive real data. - example1</h1>

<hr />

<script type="text/javascript">

//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[

var visitor_name = prompt("What's your name?","");

var curdate = new Date();

curdate.setMonth(curdate.getMonth() + 6);

var cookie_date = curdate.toUTCString();

final_cookie = "my_cookie=" + encodeURIComponent(visitor_name) + ";expires_on = " +


cookie_date;

document.cookie = final_cookie;

alert(final_cookie);

//]]>

</script>

</body>

</html>

Copy

View the example in the browser

Example: Retrieves values from cookie

[VAPM,Almala-Inst.Code-1095
]9 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

In the following web document, we will read the stored cookie and retrieves its value.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />

<title>JavaScript : Retrieve values from a cookie - example1</title>

</head>

<body>

<h1 style="color: red">JavaScript : Retrieve values from a cookie - example1</h1>

<hr />

<script type="text/javascript">

//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[

var search_cookie = "my_cookie" + "="

if (document.cookie.length > 0)

// Search for a cookie.

offset = document.cookie.indexOf(search_cookie)

if (offset != -1)

offset += search_cookie.length

// set index of beginning of value

end = document.cookie.indexOf(";",offset)

if (end == -1)

[VAPM,Almala-Inst.Code-1095
]10 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

end = document.cookie.length

alert(decodeURIComponent(document.cookie.substring(offset, end)))

//]]>

</script>

</head>

</body>

</html>

Copy

View the example in the browser

JavaScript: Cookies A Real Example

In the following web document, if a visitor registered his name, his name will be displayed if he
returns back to this page for the next nine months. When the visitor registered his name a cookie
is stored in the visitor hard drive, to delete this cookie see the next example.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />

<title>JavaScript Cookie</title>

<script type="text/javascript">

[VAPM,Almala-Inst.Code-1095
]11 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[

function register(name)

var curdate = new Date();

curdate.setMonth(curdate.getMonth() + 9);

cookieExpires = curdate.toUTCString();

final_cookie = "mycookie=" + encodeURIComponent(name) + ";expires_on = " +


cookieExpires;

document.cookie = final_cookie;

function getCookie(cookie_name)

var search_cookie = cookie_name + "="

if (document.cookie.length > 0)

start_position = document.cookie.indexOf(search_cookie)

if (start_position!= -1)

start_position += search_cookie.length

end_position = document.cookie.indexOf(";", start_position)

if (end_position == -1)

end_position = document.cookie.length

return (decodeURIComponent(document.cookie.substring(start_position, end_position)))

[VAPM,Almala-Inst.Code-1095
]12 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

//]]>

</script>

</head>

<body>

<h1 style="color: red">JavaScript Cookie</h1>

<hr />

<script type="text/javascript">

//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[

var username = getCookie("mycookie")

if (username)

document.write("Welcome Back, ", username)

if (username == null)

document.write("You haven't been here in the last nine months...")

document.write("When you return to this page in next nine months, ");

document.write("your name will be displayed...with Welcome.");

document.write('<form onsubmit = "return false">');

document.write('<p>Enter your name: </p>');

document.write('<input type="text" name="username" size="40">');

document.write('<input type = "button" value= "Register"');

document.write('onClick="register(this.form.username.value); history.go(0)">');

document.write('</form>');
[VAPM,Almala-Inst.Code-1095
]13 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

//]]>

</script>

</body>

</html>

Copy

View the example in the browser

To delete the above cookie from your hard drive use the following web document.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />

<title>JavaScript Cookie - example1</title>

<script type="text/javascript">

//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[

function register(name)

var nowDate = new Date();

nowDate.setMonth(nowDate.getMonth() + 9);

cookieExpires = nowDate.toUTCString();

final_cookie = "mycookie=" + encodeURIComponent(name) + ";expires_on = " +


cookieExpires;

document.cookie = final_cookie;

[VAPM,Almala-Inst.Code-1095
]14 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

function getCookie(cookie_name)

var search_cookie = cookie_name + "="

if (document.cookie.length > 0)

start_position = document.cookie.indexOf(search_cookie)

if (start_position!= -1)

start_position += search_cookie.length

end_position = document.cookie.indexOf(";", start_position)

if (end_position == -1)

end_position = document.cookie.length

return (decodeURIComponent(document.cookie.substring(start_position, end_position)))

//]]>

</script>

</head>

<body>

<h1 style="color: red">JavaScript Cookie - example1</h1>

<hr />

<script type="text/javascript">

//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[
[VAPM,Almala-Inst.Code-1095
]15 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

var yourname = getCookie("mycookie")

if (yourname)

document.write("Welcome Back, ", yourname)

if (yourname == null)

document.write("You haven't been here in the last nine months...")

document.write("When you return to this page in next nine months, ");

document.write("your name will be displayed...with Welcome.");

document.write('<form onsubmit = "return false">');

document.write('<p>Enter your name: </p>');

document.write('<input type="text" name="username" size="40">');

document.write('<input type = "button" value= "Register"');

document.write('onClick="register(this.form.username.value); history.go(0)">');

document.write('</form>');

//]]>

</script>

</body>

</html>

<!DOCTYPE html>

<html>

<head>

[VAPM,Almala-Inst.Code-1095
]16 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

</head>

<body>

<select id="color" onchange="display()">

<option value="Select Color">Select Color</option>

<option value="yellow">Yellow</option>

<option value="green">Green</option>

<option value="red">Red</option>

</select>

<script type="text/javascript">

function display()

var value = document.getElementById("color").value;

if (value != "Select Color")

document.bgColor = value;

</script>

</body>

</html>

[VAPM,Almala-Inst.Code-1095
]17 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

JavaScript Cookies
A cookie is an amount of information that persists between a server-side and a client-side.
A web browser stores this information at the time of browsing.

A cookie contains the information as a string generally in the form of a name-value pair
separated by semi-colons. It maintains the state of a user and remembers the user's
information among all the web pages.

How Cookies Works?


o When a user sends a request to the server, then each of that request is treated as a
new request sent by the different user.
o So, to recognize the old user, we need to add the cookie with the response from the
server.
o browser at the client-side.
o Now, whenever a user sends a request to the server, the cookie is added with that
request automatically. Due to the cookie, the server recognizes the users.

next →← prev

JavaScript Cookies
A cookie is an amount of information that persists between a server-side and a client-
side. A web browser stores this information at the time of browsing.

A cookie contains the information as a string generally in the form of a name-value pair
separated by semi-colons. It maintains the state of a user and remembers the user's
information among all the web pages.

[VAPM,Almala-Inst.Code-1095
]18 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

How Cookies Works?


o When a user sends a request to the server, then each of that request is treated as
a new request sent by the different user.
o So, to recognize the old user, we need to add the cookie with the response from
the server.
o browser at the client-side.
o Now, whenever a user sends a request to the server, the cookie is added with
that request automatically. Due to the cookie, the server recognizes the users.

How to create a Cookie in JavaScript?


In JavaScript, we can create, read, update and delete a cookie by
using document.cookie property.

The following syntax is used to create a cookie:

1. document.cookie="name=value";

[VAPM,Almala-Inst.Code-1095
]19 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Form Object

 Form object represents an HTML form.


 It is used to collect user input through elements like text fields, check box and radio button,
select option, text area, submit buttons and etc.

Form Object:
form object is a Browser object of JavaScript used to access an HTML form. If a user wants to
access all forms within a document then he can use the forms array. The form object is actually a
property of document object that is uniquely created by the browser for each form present in a
document. The properties and methods associated with form object are used to access the form
fields, attributes and controls associated with forms.

Syntax:
<form> . . . </form>

action:
action property of form object is used to access the action attribute present in HTML associated
with the <form> tag. This property is a read or write property and its value is a string.

elements[]:
elements property of form object is an array used to access any element of the form. It contains
all fields and controls present in the form. The user can access any element associated with the
form by using the looping concept on the elements array.

encoding:
The encoding property of a form object is used to access the enctype attribute present in HTML
associated with the <form> tag. This property is a read or write property and its value is a string.
This property helps determine the way of encoding the form data.

length:
length property of form object is used to specify the number of elements in the form. This
denotes the length of the elements array associated with the form.

method:
method property of form object is used to access the method attribute present in HTML
associated with the <form> tag. This property is a read or write property and its value is a string.
This property helps determine the method by which the form is submitted.

name:
name property of form object denotes the form name.

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

button:
The button property of form object denotes the button GUI control placed in the form.

checkbox:
checkbox property of form object denotes the checkbox field placed in the form.

FileUpload:
FileUpload property of form object denotes the file upload field placed in the form..

hidden:
The hidden property of form object denotes the hidden field placed in the form.

password:
password property of form object denotes the object that is placed as a password field in the
form.

radio:
radio property of form object denotes the radio button field placed in the form.

reset:
As the name implies, the reset property of form object denotes the object placed as reset button
in the form.

select:
select property of form object denotes the selection list object placed in the form.

submit:
submit property of form object denotes the submit button field that is placed in the form.

text:
text property of form object denotes the text field placed in the form.

textarea:
textarea property of form object denotes the text area field placed in the form.

An example to understand the above explanations in detail:

<FORM NAME="exforsys" ACTION="" METHOD="GET">


Input Values:<BR>
<INPUT TYPE="text" NAME="test" VALUE=""><P>
<INPUT TYPE="button" NAME="example" VALUE="Click"onClick="testfunc(this.form)">
</FORM>
Here the FORM NAME="exforsys" creates and denotes the name of the form. The user can refer
to the form in his or her code of JavaScript by the name exforsys. The form name given must
follow the naming conventions or rules of JavaScript’s variable or function naming rules. The

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

next word, ACTION="" tells the way the user wants the browser to handle the form when it is
submitted to a CGI program running on the server. It can also be left as not specified with any of
the above properties. This means the URL for the CGI program is then omitted.

The METHOD="GET" defines that the method data is passed to the server when the form is
submitted.

INPUT TYPE="text" defines the object used as a text box with the name of the text box as a test
with no initial value specified. INPUT TYPE="button" defines the object used as a button with
the name of the button object as an example. The value is specified as Click and when the button
is clicked, the onClick event handler fires and the function associated with it (testfunc(this.form))
is called.

Methods of form object:


 reset()
 submit()
 handleEvent()
reset():
reset() method of form object is used to reset a form.

submit():
submit() method of form object is used to submit a form.

handleEvent():
handleEvent() method of form object is used to start or invoke a form’s event handler for a
specified event.

Hidden Object

 Hidden object represents a hidden input field in an HTML form and it is invisible to the user.
 This object can be placed anywhere on the web page.
 It is used to send hidden form of data to a server.
Syntax:
<input type= ―hidden‖>

Hidden Object Properties

Property Description

Name It sets and returns the value of the name attribute of the hidden input field.

Type It returns type of a form element.

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Value It sets or returns the value of the value attribute of the hidden input field.

3. Password Object

 Password object represents a single-line password field in an HTML form.


 The content of a password field will be masked – appears as spots or asterisks in the browser
using password object.
Syntax:
<input type= ―password‖>

Password Object Properties

Property Description

defaultValue It sets or returns the default value of a password field.

maxLength It sets or returns the maximum number of characters allowed in a password filed.

Name It sets or returns the value of the name attribute of a password field.

readOnly It sets or returns whether a password fields is read only or not.

Size It sets or returns the width of a password field.

Value It sets or returns the value of the attribute of the password field.

Password Object Methods

Method Description

select() It selects the content of a password field.

4. Checkbox Object

 Check box object represents a checkbox in an HTML form.

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

 It allows the user to select one or more options from the available choices.
Syntax:
<input type= ―checkbox‖>

Checkbox Object Properties

Property Description

Name It sets or returns the name of the checkbox.

Type It returns the value ―check‖.

Value It sets or returns the value of the attribute of a checkbox.

checked It sets or returns the checked state of a checkbox.

defaultChecked It returns the default value of the checked attribute.

Checkbox Object Methods

Method Description

click() It sets the checked property.

5. Select Object

 Select object represents a dropdown list in an HTML form.


 It allows the user to select one or more options from the available choices.
Syntax:
<select> … </select>

Select Object Collections

Collection Description

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

options It returns a collection of all the options in a dropdown list.

Select Object Properties

Property Description

Length It returns the number of options in a dropdown list.

selectedIndex It sets or returns the index of the selected option in a dropdown list.

Type It returns a type of form element.

name It returns the name of the selection list.

Select Object Methods

Method Description

add() It adds an option to a dropdown list.

remove() It removes an option from a dropdown list.

6. Option Object

 Option object represents an HTML <option> element.


 It is used to add items to a select element.
Syntax:
<option value> . . . </option>

Option Object Properties

Property Description

Index It sets or returns the index position of an option in a dropdown list.

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Text It sets or returns the text of an option element.

defaultSelected It determines whether the option is selected by default.

Value It sets or returns the value to the server if the option was selected.

Prototype It is used to create additional properties.

Option Object Methods

Methods Description

blur() It removes the focus from the option.

focus() It gives the focus to the option.

Example : Simple Program on Option Object Method

<html>
<head>
<script type="text/javascript">
function optionfruit(select)
{
var a = select.selectedIndex;
var fav = select.options[a].value;
if(a==0)
{
alert("Please select a fruit");
}
else
{
document.write("Your Favorite Fruit is <b>"+fav+".</b>");
}

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

}
</script>
</head>
<body>
<form>
List of Fruits:
<select name="fruit">
<option value="0">Select a Fruit</option>
<option value="Mango">Mango</option>
<option value="Apple">Apple</option>
<option value="Banana">Banana</option>
<option value="Strawberry">Strawberry</option>
<option value="Orange">Orange</option>
</select>
<input type="button" value="Select" onClick="optionfruit(this.form.fruit);">
</form>
</body>
</html>

Output:

Your Favorite Fruit is Mango.

7. Radio Object

Radio object represents a radio button in an HTML form.

Syntax:
<input type= ―radio‖>

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Radio Object Properties

Property Description

Checked It sets or returns the checked state of a radio button.

defaultChecked Returns the default value of the checked attribute.

Name It sets or returns the value of the name attribute of a radio button.

Type It returns the type of element which is radio button.

Value It sets or returns the value of the radio button.

Radio Object Methods

Method Description

blur() It takes the focus away from the radio button.

click() It acts as if the user clicked the button.

focus() It gives the focus to the radio button.

8. Text Object

Text object represents a single-line text input field in an HTML form.

Syntax:
<input type= ―text‖>

Text Object Properties

Property Description

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Value It sets or returns the value of the text field.

defaultValue It sets or returns the default value of a text field.

Name It sets or returns the value of the name attribute of a text field.

maxLength It sets or returns the maximum number of characters allowed in a text field.

readOnly It sets or returns whether a text field is read-only or not.

Size It sets or returns the width of a text field.

Type It returns type of form element of a text field.

9. Textarea Object

Textarea object represents a text-area in an HTML form.

Syntax:
<textarea> . . . </textarea>

Textarea Object Properties

Property Description

Value It sets or returns the value of the text field.

defaultValue It sets or returns the default value of a text field.

Name It sets or returns the value of the name attribute of a text field.

Type It returns type of form element of a text field.

Rows It displays the number of rows in a text area.

Cols It displays the number of columns in a text area.

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

https://www.tutorialride.com/javascript/javascript-dom-frame-object.htm

JavaScript Events

In this tutorial you will learn how to handle events in JavaScript.

Understanding Events and Event Handlers


An event is something that happens when user interact with the web page, such as when he
clicked a link or button, entered text into an input box or textarea, made selection in a select box,
pressed key on the keyboard, moved the mouse pointer, submits a form, etc. In some cases, the
Browser itself can trigger the events, such as the page load and unload events.
When an event occur, you can use a JavaScript event handler (or an event listener) to detect them
and perform specific task or set of tasks. By convention, the names for event handlers always
begin with the word "on", so an event handler for the click event is called onclick, similarly an
event handler for the load event is called onload, event handler for the blur event is called onblur,
and so on.
There are several ways to assign an event handler. The simplest way is to add them directly to
the start tag of the HTML elements using the special event-handler attributes. For example, to
assign a click handler for a button element, we can use onclick attribute, like this:

Example
Try this code »

<button type="button" onclick="alert('Hello World!')">Click Me</button>


However, to keep the JavaScript seperate from HTML, you can set up the event handler in an
external JavaScript file or within the <script> and </script> tags, like this:

Example
Try this code »

<button type="button" id="myBtn">Click Me</button>


<script>
function sayHello() {
alert('Hello World!');
}
document.getElementById("myBtn").onclick = sayHello;
</script>
Note: Since HTML attributes are case-insensitive so onclick may also be written
as onClick, OnClick or ONCLICK. But its value is case-sensitive.

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

In general, the events can be categorized into four main groups — mouse events, keyboard
events, form events and document/window events. There are many other events, we will learn
about them in later chapters. The following section will give you a brief overview of the most
useful events one by one along with the real life practice examples.

Mouse Events
A mouse event is triggered when the user click some element, move the mouse pointer over an
element, etc. Here're some most important mouse events and their event handler.

The Click Event (onclick)


The click event occurs when a user clicks on an element on a web page. Often, these are form
elements and links. You can handle a click event with an onclick event handler.
The following example will show you an alert message when you click on the elements.

Example
Try this code »

<button type="button" onclick="alert('You have clicked a button!');">Click Me</button>


<a href="#" onclick="alert('You have clicked a link!');">Click Me</a>

The Contextmenu Event (oncontextmenu)


The contextmenu event occurs when a user clicks the right mouse button on an element to open a
context menu. You can handle a contextmenu event with an oncontextmenu event handler.
The following example will show an alert message when you right-click on the elements.

Example
Try this code »

<button type="button" oncontextmenu="alert('You have right-clicked a button!');">Right Click


on Me</button>
<a href="#" oncontextmenu="alert('You have right-clicked a link!');">Right Click on Me</a>

The Mouseover Event (onmouseover)


The mouseover event occurs when a user moves the mouse pointer over an element.
You can handle the mouseover event with the onmouseover event handler. The following
example will show you an alert message when you place mouse over the elements.

Example
Try this code »

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

<button type="button" onmouseover="alert('You have placed mouse pointer over a


button!');">Place Mouse Over Me</button>
<a href="#" onmouseover="alert('You have placed mouse pointer over a link!');">Place Mouse
Over Me</a>

The Mouseout Event (onmouseout)


The mouseout event occurs when a user moves the mouse pointer outside of an element.
You can handle the mouseout event with the onmouseout event handler. The following example
will show you an alert message when the mouseout event occurs.

Example
Try this code »

<button type="button" onmouseout="alert('You have moved out of the button!');">Place Mouse


Inside Me and Move Out</button>
<a href="#" onmouseout="alert('You have moved out of the link!');">Place Mouse Inside Me
and Move Out</a>

Keyboard Events
A keyboard event is fired when the user press or release a key on the keyboard. Here're some
most important keyboard events and their event handler.

The Keydown Event (onkeydown)


The keydown event occurs when the user presses down a key on the keyboard.
You can handle the keydown event with the onkeydown event handler. The following example
will show you an alert message when the keydown event occurs.

Example
Try this code »

<input type="text" onkeydown="alert('You have pressed a key inside text input!')">


<textarea onkeydown="alert('You have pressed a key inside textarea!')"></textarea>

The Keyup Event (onkeyup)


The keyup event occurs when the user releases a key on the keyboard.
You can handle the keyup event with the onkeyup event handler. The following example will
show you an alert message when the keyup event occurs.
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Example
Try this code »

<input type="text" onkeyup="alert('You have released a key inside text input!')">


<textarea onkeyup="alert('You have released a key inside textarea!')"></textarea>

The Keypress Event (onkeypress)


The keypress event occurs when a user presses down a key on the keyboard that has a character
value associated with it. For example, keys like Ctrl, Shift, Alt, Esc, Arrow keys, etc. will not
generate a keypress event, but will generate a keydown and keyup event.
You can handle the keypress event with the onkeypress event handler. The following example
will show you an alert message when the keypress event occurs.

Example
Try this code »

<input type="text" onkeypress="alert('You have pressed a key inside text input!')">


<textarea onkeypress="alert('You have pressed a key inside textarea!')"></textarea>

Form Events
A form event is fired when a form control receive or loses focus or when the user modify a form
control value such as by typing text in a text input, select any option in a select box etc. Here're
some most important form events and their event handler.

The Focus Event (onfocus)


The focus event occurs when the user gives focus to an element on a web page.
You can handle the focus event with the onfocus event handler. The following example will
highlight the background of text input in yellow color when it receives the focus.

Example
Try this code »

<script>
function highlightInput(elm){
elm.style.background = "yellow";
}
</script>

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

<input type="text" onfocus="highlightInput(this)">


<button type="button">Button</button>
Note: The value of this keyword inside an event handler refers to the element which has the
handler on it (i.e. where the event is currently being delivered).

The Blur Event (onblur)


The blur event occurs when the user takes the focus away from a form element or a window.
You can handle the blur event with the onblur event handler. The following example will show
you an alert message when the text input element loses focus.

Example
Try this code »

<input type="text" onblur="alert('Text input loses focus!')">


<button type="button">Submit</button>
To take the focus away from a form element first click inside of it then press the tab key on the
keyboard, give focus on something else, or click outside of it.

The Change Event (onchange)


The change event occurs when a user changes the value of a form element.
You can handle the change event with the onchange event handler. The following example will
show you an alert message when you change the option in the select box.

Example
Try this code »

<select onchange="alert('You have changed the selection!');">


<option>Select</option>
<option>Male</option>
<option>Female</option>
</select>

The Submit Event (onsubmit)


The submit event only occurs when the user submits a form on a web page.
You can handle the submit event with the onsubmit event handler. The following example will
show you an alert message while submitting the form to the server.

Example
Try this code »

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

<form action="action.php" method="post" onsubmit="alert('Form data will be submitted to the


server!');">
<label>First Name:</label>
<input type="text" name="first-name" required>
<input type="submit" value="Submit">
</form>

Document/Window Events
Events are also triggered in situations when the page has loaded or when user resize the browser
window, etc. Here're some most important document/window events and their event handler.

The Load Event (onload)


The load event occurs when a web page has finished loading in the web browser.
You can handle the load event with the onload event handler. The following example will show
you an alert message as soon as the page finishes loading.

Example
Try this code »

<body onload="window.alert('Page is loaded successfully!');">


<h1>This is a heading</h1>
<p>This is paragraph of text.</p>
</body>

The Unload Event (onunload)


The unload event occurs when a user leaves the current web page.
You can handle the unload event with the onunload event handler. The following example will
show you an alert message when you try to leave the page.

Example
Try this code »

<body onunload="alert('Are you sure you want to leave this page?');">


<h1>This is a heading</h1>
<p>This is paragraph of text.</p>
</body>

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

The Resize Event (onresize)


The resize event occurs when a user resizes the browser window. The resize event also occurs in
situations when the browser window is minimized or maximized.
You can handle the resize event with the onresize event handler. The following example will
show you an alert message when you resize the browser window to a new width and height.

Example
Try this code »

<p id="result"></p>
<script>
function displayWindowSize() {
var w = window.outerWidth;
var h = window.outerHeight;
var txt = "Window size: width=" + w + ", height=" + h;
document.getElementById("result").innerHTML = txt;
}
window.onresize = displayWindowSize;
</script>

https://www.tutorialrepublic.com/javascript-tutorial/javascript-events.php

<!DOCTYPE html>

<html>

<body>

<form>

<select id="mySelect" size="8">

<option>Apple</option>

<option>Pear</option>

<option>Banana</option>

<option>Orange</option>

</select>

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

</form>

<br>

<p>Click the button to add a "Kiwi" option at the end of the dropdown list.</p>

<button type="button" onclick="myFunction()">Insert option</button>

******************************************************************************

<script>

function myFunction() {

var x = document.getElementById("mySelect");

var option = document.createElement("option");

option.text = prompt("Enter the Student Name=");

x.add(option);

</script>

</body>

</html>

function getOption(){

var select = document.getElementById("dynamic-select");

if(select.options.length > 0) {

var option = select.options[select.selectedIndex];

alert("Text: " + option.text + "\nValue: " + option.value);

} else {

window.alert("Select box is empty");

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

function addOption(){

var select = document.getElementById("dynamic-select");

select.options[select.options.length] = new Option('New Element', '0', false, false);

function removeOption(){

var select = document.getElementById("dynamic-select");

select.options[select.selectedIndex] = null;

function removeAllOptions(){

var select = document.getElementById("dynamic-select");

select.options.length = 0;

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Dynamically add/remove options select - JavaScript</title>

</head>

<body>

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

<select id="dynamic-select">

<option value="1">one</option>

<option value="2">two</option>

<option value="3">three</option>

</select>

<button onclick="getOption()">get item</button>

<button onclick="addOption()">add item</button>

<button onclick="removeOption()">remove item</button>

<button onclick="removeAllOptions()">remove all</button>

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

</body>

</html>

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Deleting Properties
The delete keyword deletes a property from an object:

Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
delete person.age;

The delete keyword deletes both the value of the property and the property
itself.

After deletion, the property cannot be used before it is added back again.

The delete operator is designed to be used on object properties. It has no


effect on variables or functions.

The delete operator should not be used on predefined JavaScript object


properties. It can crash your application.

JavaScript Arrays
An array is an object that can store a collection of items. Arrays become really useful
when you need to store large amounts of data of the same type. Suppose you want to store
details of 500 employees. If you are using variables, you will have to create 500 variables
whereas you can do the same with a single array. You can access the items in an array by
referring to its indexnumber and the index of the first element of an array is zero.

JavaScript arrays are used to store multiple values in a single variable.

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

What is an Array?
An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

var car1 = "Saab";


var car2 = "Volvo";
var car3 = "BMW";

However, what if you want to loop through the cars and find a specific one? And what if you
had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name, and you can access the values by
referring to an index number.

Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.

Syntax:
var array_name = [item1, item2, ...];
Example
var cars = ["Saab", "Volvo", "BMW"];

Spaces and line breaks are not important. A declaration can span multiple lines:
Example
var cars = [
"Saab",
"Volvo",
"BMW"
];

JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.

There are 3 ways to construct array in JavaScript

1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

1) JavaScript array literal


The syntax of creating array using array literal is given below:

var arrayname=[value1,value2.....valueN];

As you can see, values are contained inside [ ] and separated by , (comma).

Let’s see the simple example of creating and using array in JavaScript.

<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>

2) JavaScript Array directly (new keyword)


The syntax of creating array directly is given below:

1. var arrayname=new Array();

Here, new keyword is used to create instance of array.

Let’s see the example of creating array directly.

<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";

for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

3) JavaScript array constructor (new keyword)


Here, you need to create instance of array by passing arguments in constructor so that we don't have to
provide value explicitly.

The example of creating object by array constructor is given below.

<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>

Access the Elements of an Array


You access an array element by referring to the index number.

This statement accesses the value of the first element in cars:


var name = cars[0];

Example
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];

Note: Array indexes start with 0.

[0] is the first element. [1] is the second element

Adding Array Elements


The easiest way to add a new element to an array is using the push() method:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); // adds a new element (Lemon) to fruits

New element can also be added to an array using the length property:

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits

WARNING !

Adding elements with high indexes can create undefined "holes" in an array:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[6] = "Lemon"; // adds a new element (Lemon) to fruits

The Difference between Arrays and Objects


In JavaScript, arrays use numbered indexes.

In JavaScript, objects use named indexes.

Arrays are a special kind of objects, with numbered indexes.

When to Use Arrays. When to use Objects.


 JavaScript does not support associative arrays.
 You should use objects when you want the element names to be strings (text).
 You should use arrays when you want the element names to be numbers.

JavaScript Array join () Method


(Combining an Array elements into a String)
Example
Convert the elements of an array into a string:

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


var energy = fruits.join();

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Definition and Usage


The join() method returns the array as a string.

The elements will be separated by a specified separator. The default separator is comma (,).

Note: this method will not change the original array.

JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function many times to reuse the
code.

Advantage of JavaScript function

There are mainly two advantages of JavaScript functions.


1. Code reusability: We can call a function several times so it save coding.
2. Less coding: It makes our program compact. We don’t need to write many lines of code each time to
perform a common task.

JavaScript Function Syntax


The syntax of declaring function is given below.
function functionName([arg1, arg2, ...argN]){
//code to be executed
}

JavaScript Functions can have 0 or more arguments.

JavaScript Function Example


Let’s see the simple example of function in JavaScript that does not has arguments.
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

JavaScript Function Arguments


We can call function by passing arguments. Let’s see the example of function that has one argument.
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>

Function with Return Value


We can call function that returns a value and use it in our program. Let’s see the
example of function that returns value.
<script>
function getInfo(){
return "hello javatpoint! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>

JavaScript Function Object


In JavaScript, the purpose of Function constructor is to create a new Function object. It
executes the code globally. However, if we call the constructor directly, a function is created
dynamically but in an unsecured way.

Syntax
1. new Function ([arg1[, arg2[, ....argn]],] functionBody)

Parameter
arg1, arg2, .... , argn - It represents the argument used by function.

functionBody - It represents the function definition.

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

JavaScript Function Methods


Let's see function methods with description.

Method Description

apply() It is used to call a function contains this value and a single array of
arguments.

bind() It is used to create a new function.

call() It is used to call a function contains this value and an argument list.

toString() It returns the result in a form of a string.

JavaScript Function Object Examples


Example 1
Let's see an example to display the sum of given numbers.
<script>
var add=new Function("num1","num2","return num1+num2");
document.writeln(add(2,5));
</script>

Example 2
Let's see an example to display the power of provided value.
<script>
var pow=new Function("num1","num2","return Math.pow(num1,num2)");
document.writeln(pow(2,3));
</script>

What is Function in JavaScript?

Functions are very important and useful in any programming language as they make the
code reusable A function is a block of code which will be executed only if it is called. If you
have a few lines of code that needs to be used several times, you can create a function
including the repeating lines of code and then call the function wherever you want.

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

How to Create a Function in JavaScript

1. Use the keyword function followed by the name of the function.


2. After the function name, open and close parentheses.
3. After parenthesis, open and close curly braces.
4. Within curly braces, write your lines of code.

Syntax:
function functionname()

lines of code to be executed

Try this yourself:


This code is editable. Click Run to Execute

<html>

<head>

<title>Functions!!!</title>

<script type="text/javascript">

function myFunction()

document.write("This is a simple function.<br />");

myFunction();

</script>

</head>

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

<body>

</body>

</html>

Function with Arguments

You can create functions with arguments as well. Arguments should be specified within
parenthesis

Syntax:
function functionname(arg1, arg2)

lines of code to be executed

JavaScript Return Value

You can also create JS functions that return values. Inside the function, you need to use the
keyword return followed by the value to be returned.

Syntax:
function functionname(arg1, arg2)

lines of code to be executed

return val1;

Try this yourself:


This code is editable. Click Run to Execute
<html>
<head>
<script type="text/javascript">
function returnSum(first, second)
{
var sum = first + second;

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

return sum;
}
var firstNo = 78;
var secondNo = 22;
document.write(firstNo + " + " + secondNo + " = " + returnSum(firstNo,secondNo));
</script>
</head>
<body>
</html>

Introduction
A string is a sequence of one or more characters that may consist of letters, numbers, or
symbols. Each character in a JavaScript string can be accessed by an index number, and
all strings have methods and properties available to them.

String Primitives and String Objects


First, we will clarify the two types of strings. JavaScript differentiates between the string
primitive, an immutable datatype, and the String object.

In order to test the difference between the two, we will initialize a string primitive and a
string object.

// Initializing a new string primitive


const stringPrimitive = "A new string.";

// Initializing a new String object


const stringObject = new String("A new string.");
We can use the typeof operator to determine the type of a value. In the first example,
we simply assigned a string to a variable.

typeof stringPrimitive;
Output
string
In the second example, we used new String() to create a string object and assign it to
a variable.

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

typeof stringObject;
Output
Object

Most of the time you will be creating string primitives. JavaScript is able to access and
utilize the built-in properties and methods of the String object wrapper without
actually changing the string primitive you've created into an object.

While this concept is a bit challenging at first, you should be aware of the distinction
between primitive and object. Essentially, there are methods and properties available to
all strings, and in the background JavaScript will perform a conversion to object and
back to primitive every time a method or property is called.

How Strings are Indexed


Each of the characters in a string correspond to an index number, starting with 0.

To demonstrate, we will create a string with the value How are you?.

H o w a r e y o u ?

0 1 2 3 4 5 6 7 8 9 10 11

The first character in the string is H, which corresponds to the index 0. The last character
is ?, which corresponds to 11. The whitespace characters also have an index, at 3 and 7.

Being able to access every character in a string gives us a number of ways to work with
and manipulate strings.

1. charAt(x) Returns the character at the “x” position within the string.

//charAt(x)

var myString = 'jQuery FTW!!!';

console.log(myString.charAt(7));

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

//output: F

2. charCodeAt(x) Returns the Unicode value of the character at position “x” within the
string.

//charAt(position)

var message="jquery4u"

//alerts "q"

alert(message.charAt(1))

3. concat(v1, v2,…) Combines one or more strings (arguments v1, v2 etc) into the
existing one and returns the combined string. Original string is not modified.

//concat(v1, v2,..)

var message="Sam"

var final=message.concat(" is a"," hopeless romantic.")

//alerts "Sam is a hopeless romantic."

alert(final)

4. fromCharCode(c1, c2,…) Returns a string created by using the specified sequence


of Unicode values (arguments c1, c2 etc). Method of String object, not String instance.
For example: String.fromCharCode().

//fromCharCode(c1, c2,...)

console.log(String.fromCharCode(97,98,99,120,121,122))

//output: abcxyz

console.log(String.fromCharCode(72,69,76,76,79))

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

//output: HELLO

//(PS - I have no idea why you would use this? any ideas?)

Also see: Full List of JavaScript Character Codes

5. indexOf(substr, [start]) Searches and (if found) returns the index number of the
searched character or substring within the string. If not found, -1 is returned. “Start” is
an optional argument specifying the position within string to begin the search. Default is
0.

//indexOf(char/substring)

var sentence="Hi, my name is Sam!"

if (sentence.indexOf("Sam")!=-1)

alert("Sam is in there!")

6. lastIndexOf(substr, [start]) Searches and (if found) returns the index number of the
searched character or substring within the string. Searches the string from end to
beginning. If not found, -1 is returned. “Start” is an optional argument specifying the
position within string to begin the search. Default is string.length-1.

//lastIndexOf(substr, [start])

var myString = 'javascript rox';

console.log(myString.lastIndexOf('r'));

//output: 11

7. match(regexp) Executes a search for a match within a string based on a regular


expression. It returns an array of information or null if no match is found.

//match(regexp) //select integers only

var intRegex = /[0-9 -()+]+$/;

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

var myNumber = '999';

var myInt = myNumber.match(intRegex);

console.log(isInt);

//output: 999

var myString = '999 JS Coders';

var myInt = myString.match(intRegex);

console.log(isInt);

//output: null

Also see: jQuery RegEx Examples to use with .match()

8. replace(regexp/substr, replacetext) Searches and replaces the regular expression


(or sub string) portion (match) with the replaced text instead.

//replace(substr, replacetext)

var myString = '999 JavaScript Coders';

console.log(myString.replace(/JavaScript/i, "jQuery"));

//output: 999 jQuery Coders

//replace(regexp, replacetext)

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

var myString = '999 JavaScript Coders';

console.log(myString.replace(new RegExp( "999", "gi" ), "The"));

//output: The JavaScript Coders

9. search(regexp) Tests for a match in a string. It returns the index of the match, or -1 if
not found.

//search(regexp)

var intRegex = /[0-9 -()+]+$/;

var myNumber = '999';

var isInt = myNumber.search(intRegex);

console.log(isInt);

//output: 0

var myString = '999 JS Coders';

var isInt = myString.search(intRegex);

console.log(isInt);

//output: -1

10. slice(start, [end]) Returns a substring of the string based on the “start” and “end”
index arguments, NOT including the “end” index itself. “End” is optional, and if none is
specified, the slice includes all characters from “start” to end of string.

//slice(start, end)

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

var text="excellent"

text.slice(0,4) //returns "exce"

text.slice(2,4) //returns "ce"

11. split(delimiter, [limit]) Splits a string into many according to the specified delimiter,
and returns an array containing each element. The optional “limit” is an integer that lets
you specify the maximum number of elements to return.

//split(delimiter)

var message="Welcome to jQuery4u"

//word[0] contains "We"

//word[1] contains "lcome to jQuery4u"

var word=message.split("l")

12. substr(start, [length]) Returns the characters in a string beginning at “start” and
through the specified number of characters, “length”. “Length” is optional, and if omitted,
up to the end of the string is assumed.

//substring(from, to)

var text="excellent"

text.substring(0,4) //returns "exce"

text.substring(2,4) //returns "ce"

13. substring(from, [to]) Returns the characters in a string between “from” and “to”
indexes, NOT including “to” inself. “To” is optional, and if omitted, up to the end of the
string is assumed.

//substring(from, [to])

var myString = 'javascript rox';

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

myString = myString.substring(0,10);

console.log(myString)

//output: javascript

14. toLowerCase() Returns the string with all of its characters converted to lowercase.

//toLowerCase()

var myString = 'JAVASCRIPT ROX';

myString = myString.toLowerCase();

console.log(myString)

//output: javascript rox

15. toUpperCase() Returns the string with all of its characters converted to uppercase.

//toUpperCase()

var myString = 'javascript rox';

myString = myString.toUpperCase();

console.log(myString)

//output: JAVASCRIPT ROX

JavaScript string (primitive or String object) includes default properties and


methods which you can use for different purposes.

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

String Properties
Property Description

length Returns the length of the string.

String Methods
Method Description

charAt(position) Returns the character at the specified position (in Number).

charCodeAt(position) Returns a number indicating the Unicode value of the character at the given
position (in Number).

concat([string,,]) Joins specified string literal values (specify multiple strings separated by
comma) and returns a new string.

indexOf(SearchString, Returns the index of first occurrence of specified String starting from
Position) specified number index. Returns -1 if not found.

lastIndexOf(SearchString, Returns the last occurrence index of specified SearchString, starting from
Position) specified position. Returns -1 if not found.

localeCompare(string,position) Compares two strings in the current locale.

match(RegExp) Search a string for a match using specified regular expression. Returns a
matching array.

replace(searchValue, Search specified string value and replace with specified replace Value string
replaceValue) and return new string. Regular expression can also be used as searchValue.

search(RegExp) Search for a match based on specified regular expression.

slice(startNumber, Extracts a section of a string based on specified starting and ending index
endNumber) and returns a new string.

split(separatorString, Splits a String into an array of strings by separating the string into substrings
limitNumber) based on specified separator. Regular expression can also be used as
separator.

substr(start, length) Returns the characters in a string from specified starting position through
the specified number of characters (length).

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Method Description

substring(start, end) Returns the characters in a string between start and end indexes.

toLocaleLowerCase() Converts a string to lower case according to current locale.

toLocaleUpperCase() Converts a sting to upper case according to current locale.

toLowerCase() Returns lower case string value.

toString() Returns the value of String object.

toUpperCase() Returns upper case string value.

valueOf() Returns the primitive value of the specified string object.

String Methods for Html


The following string methods convert the string as a HTML wrapper element.

Method Description

anchor() Creates an HTML anchor <a>element around string value.

big() Wraps string in <big> element.

blink() Wraps a string in <blink> tag.

bold() Wraps string in <b> tag to make it bold in HTML.

fixed() Wraps a string in <tt> tag.

fontcolor() Wraps a string in a <font color="color"> tag.

fontsize() Wraps a string in a <font size="size"> tag.

italics() Wraps a string in <i> tag.

link() Wraps a string in <a>tag where href attribute value is set to specified string.

small() Wraps a string in a <small>tag.

strike() Wraps a string in a <strike> tag.

sub() Wraps a string in a <sub>tag

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Method Description

sup() Wraps a string in a <sup>tag

VAPM,Almala-Inst.Code-1095
October 7, MR.SWAMI R.S. {MOBILE NO :- +91-8275265361]
2019

Validation Code
<html>
<head>
<script>
function validateform()
{
var
name=document.myform.name.value;
var
password=document.myform.password.v
alue;

if (name==null || name==""|| name.length<10){


alert("Name can't be blank or greater than 10 characters");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
else
{
alert("Data is Submitted")
}
}
</script>
</head>
<body>
<form name="myform" method="post" onclick="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>

Slider Show
<html>

Client Side Scripting Language-22519 1


October 7, MR.SWAMI R.S. {MOBILE NO :- +91-8275265361]
2019

<head>
<script>
Silder=new
Array('download1.jpg','download2.jpg','download3.jpg','download4.jpg','download5.jpg');
i=0;
function display(sn)
{
i=i+sn;
if(i>Silder.length-1)
{
i=0;
}
if(i<0)
{
i=Silder.length-1;
}
document.SlideID.src=Silder[i];

}
</script>
</head>
<body>
<center>
<h1>Nature ko enjoy kare!</h1>

<img src="fruit.jpg" name="SlideID" width="800" height="200"><br><br>


<button onclick="display(-1)">Back</button>
<button onclick="display(1)">Next</button></center>
</body>
</html>

Menu

<html>
<head>
<script>
function menuitem()
{
var
s=document.getElementById("select");
var str=s.options[s.selectedIndex].value;

Client Side Scripting Language-22519 2


October 7, MR.SWAMI R.S. {MOBILE NO :- +91-8275265361]
2019

alert("Selected Item is="+str);


}
</script>
<body>
<select id="select">
<option>apple</option>
<option>banana</option>
<option>oranges</option>
<option>Image4</option>
</select>
<button onclick="menuitem()">show</button>

</body>
</head>
</html>

Rollover

<html>
<body>
<a>
<img
src="Chrysanthemum.jpg"
onmouseover="src=Desert.jpg"
onmouseout="src=Koala.jpg">
</a>
</body>
</html>

Or
<html>
<head>
<script>
function display1()
{
document.pic.src='file:\\\C://Users//Public//Pictures//Sample Pictures//Desert.jpg';
document.getElementById('p').innerHTML="This Desert Image.";
}
function display2()
{
document.pic.src='file:\\\C://Users//Public//Pictures//Sample Pictures//Koala.jpg';
document.getElementById('p').innerHTML="This Koala Image.";

Client Side Scripting Language-22519 3


October 7, MR.SWAMI R.S. {MOBILE NO :- +91-8275265361]
2019

}
</script>
</head>
<body>

<a onmouseover="display1()"><h1>Dersert</h1></a>

<a onmouseout="display2()"><h1>Koala</h1></a>
<a>
<img src='file:\\\C://Users//Public//Pictures//Sample
Pictures//Chrysanthemum.jpg'name='pic'>
</a>
<p id="p">Images</p>
</body>
</html>

Intrinsic
<html>
<body>
<form name="frm1" method="post">
Name<input type="text"
name="t1"><br>
Password<input type="text"
name="t2"><br>
<button
onclick="javascript:document.forms.formn
ame.submit()">submit</button>
<button
onclick="javascript:document.forms.formn
ame.reset()">reset</button>
</form>
</body>
</html>

Dynamically
<!DOCTYPE html>
<html>
<body>

Client Side Scripting Language-22519 4


October 7, MR.SWAMI R.S. {MOBILE NO :- +91-8275265361]
2019

<form>
<select id="mySelect" size="8">
<option>Apple</option>
<option>Pear</option>
<option>VAPM</option>
<option>Banana</option>
<option>Orange</option>
</select>
</form>
<br>

<button type="button" onclick="myFunction()">Insert option</button>

<script>
function myFunction() {
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = prompt("Enter the Student Name=");
x.add(option);
}
</script>

</body>
</html>

Frame
<html>
9 <head>
<title>Example of HTML
Frames using row and Cols
attribute</title>
</head>

<frameset rows = "20%,*">


<frame src =
"D:\Shree\data0\Shree
VAPM\2019-2020\Java
Script\Chapter 5\Frame4.html" />

Client Side Scripting Language-22519 5


October 7, MR.SWAMI R.S. {MOBILE NO :- +91-8275265361]
2019

<frameset cols="50%, 50%">


<frame src =
"D:\Shree\data0\Shree VAPM\2019-2020\Java Script\Chapter 5\Frame1.html" />
<frame src =
"D:\Shree\data0\Shree VAPM\2019-2020\Java Script\Chapter 5\Frame2.html" />

</frameset>
Adhar Card Validation Program
</html>

<html>
<head>
<script>
function show()
{
adhar =
document.getElementBy
Id("txtaadhar").value;
var adharcard =
/^\d{12}$/;
var adharsixteendigit =
/^\d{16}$/;
if (adhar != '') {
if
(!adhar.match(adharcar
d))
{
alert("Invalid
Aadhar Number");
return false;
}
}
if (adhar != '')
{
if(!adhar.match(adharsixteendigit))
{
alert("Invalid Aadhar Number");
return false;
}
}
}

Client Side Scripting Language-22519 6


October 7, MR.SWAMI R.S. {MOBILE NO :- +91-8275265361]
2019

</script>
</head>
<body>
Enter the Adhar Card No.<input type="text" id="txtaadhar"><br>
<button onclick="show()">Adhar Card</button>
</body>
</html>

Client Side Scripting Language-22519 7


September
MR.SWAMI R.S. {MOBILE NO:- +91-8275265361}
17, 2019

The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.

The Browser Object Model (BOM)

There are no official standards for the Browser Object Model (BOM).

Since modern browsers have implemented (almost) the same methods and properties for
JavaScript interactivity as methods and properties of the BOM.

The Window Object

The window object is supported by all browsers. It represents the browser's window.

All global JavaScript objects, functions, and variables automatically become members of the
window object.

URL
The URL of the page to open in the new window. This argument could be blank.

windowName
A name to be given to the new window. The name can be used to refer this window again.

windowFeatures
A string that determines the various window features to be included in the popup window (like
status bar, address bar etc)

The following code opens a new browser window with standard features.

fullscreen=yes|no|1|0 Whether or not to display the browser in full-screen mode. Default is no. A
window in full-screen mode must also be in theater mode. IE only

height=pixels The height of the window. Min. value is 100

left=pixels The left position of the window. Negative values not allowed

1 |Page
location=yes|no|1|0 Whether or not to display the address field. OperaVonly
APM ALMALA
September
MR.SWAMI R.S. {MOBILE NO:- +91-8275265361}
17, 2019

menubar=yes|no|1|0 Whether or not to display the menu bar

resizable=yes|no|1|0 Whether or not the window is resizable. IE only

scrollbars=yes|no|1|0 Whether or not to display scroll bars. IE, Firefox & Opera only

status=yes|no|1|0 Whether or not to add a status bar

titlebar=yes|no|1|0 Whether or not to display the title bar. Ignored unless the calling application is an
HTML Application or a trusted dialog box

toolbar=yes|no|1|0 Whether or not to display the browser toolbar. IE and Firefox only

top=pixels The top position of the window. Negative values not allowed

width=pixels The width of the window. Min. value is 100

Window.close()
This method is used to close the window which are opened by window.open() method.
Syntax:
window.close()

Parameters: This method does not contains any parameter.


Return Value: This method does not return any value.
Below example illustrates the window.open() and window.close() method in jQuery:

2|Page VAPM ALMALA


September
MR.SWAMI R.S. {MOBILE NO:- +91-8275265361}
17, 2019

Javascript | Window Blur() and Window Focus() Method

Window.blur() Method
The blur() method is used to remove focus from the current window. i.e, It send the new open
Window to the background.
Syntax:
Window.blur()

Parameter: It does not require any parameters.


Return Value: It does not Return any value.
window.html
Window.focus() Method
The focus() method is used to focus on the new open window. i.e bringing back the blur window
to the foreground.
Syntax:
window.focus()

Parameter: It does not require any parameters.


Return Value: It does not Return any value.
Below example illustrates the window.blur() and window.focus() method in JavaScript:

Javascript | Window prompt() Method


The prompt() method is used to display a dialog with an optional message prompting the user to
input some text. It is often used if the user wants to input a value before entering a page.
It returns a string containing the text entered by the user, or null.
Syntax:
prompt(message, default)

 message is a string of text to display to the user.It can be omitted if there is nothing to
show in the prompt window i.e. it is optional.
 default is a string containing the default value displayed in the text input field. It is also
optional.
prompt.html

3|Page VAPM ALMALA


September
MR.SWAMI R.S. {MOBILE NO:- +91-8275265361}
17, 2019

Javascript | Window scrollTo() Method

The Window scrollTo() method is used to scroll to a particular set of coordinates in the
document.
Syntax:
window.scrollTo(x-coord, y-coord)
Parameters: The scrollTo() method accepts two parameters as described below:
 x-coord: It is the pixel along the horizontal axis of the document that is displayed in the
upper left. It is the required field.
 y-coord: It is the pixel along the vertical axis of the document that is displayed in the upper
left. It is the required field.

Note :- //Scrolling the document to position "250"

//horizontally and "110" vertically

ScrollBarDemo.html

ScrollBarDemo2.html

Changing the Contents of Window

By writing some text to the newly created window we can change the contents of a window.

New message using writes write () method.

multiple.html

JavaScript Security

Since its release, there have been several JavaScript security issues that have gained widespread
attention. For one, the way JavaScript interacts with the DOM poses a risk for end users by
enabling malicious actors to deliver scripts over the web and run them on client computers.
There are two measures that can be taken to contain this JavaScript security risk. First is
sandboxing, or running scripts separately so that they can only access certain resources and
perform specific tasks. The second measure is implementing the same origin policy, which
prevents scripts from one site from accessing data that is used by scripts from other sites. Many
JavaScript security vulnerabilities are the result of browser authors failing to take these measures
to contain DOM-based JavaScript security risks.

Common JavaScript Security Vulnerabilities

4|Page VAPM ALMALA


September
MR.SWAMI R.S. {MOBILE NO:- +91-8275265361}
17, 2019

One of the most common JavaScript security vulnerabilities is Cross-Site Scripting (XSS).
Cross-Site Scripting vulnerabilities enable attackers to manipulate websites to return malicious
scripts to visitors. These malicious scripts then execute on the client side in a manner determined
by the attacker. XSS vulnerabilities can exist when browser or application authors fail to
implement the same origin policy and can be prevented by following correct development
techniques. If XSS vulnerabilities aren’t remediated, they can result in user data theft, account
tampering, malware spreading or remote control over a user’s browser.
Another common JavaScript security vulnerability is Cross-Site Request Forgery (CSRF). Cross-
Site Request Forgery vulnerabilities allow attackers to manipulate victims’ browsers to take
unintended actions on other sites. This is possible when target sites authenticate requests solely
using cookies and attackers are able to send requests carrying users’ cookies. This JavaScript
security issue can lead to account tampering, data theft, fraud and more. Both Cross-Site
Scripting and Cross-Site Request Forgery vulnerabilities exist in the application layer and require
that correct development techniques are followed in order to be avoided.
There are a variety of other common JavaScript security issues that can increase risks for users.
These issues include improper client-server trust relationships, vulnerabilities in browser and
browser plugin code, and incorrect implementation of sandboxing or same origin policy. And for
Node.js-based server side applications, there may be many other security vulnerabilities,
including SQL Injection, Command Injection, and others. The only way for organizations to
avoid these JavaScript security risks is to develop and source applications that are free of
JavaScript security vulnerabilities. Many organizations use JavaScript security analyzers to test
for and remediate these vulnerabilities.

JavaScript Security Analyzers

JavaScript security analyzers are JavaScript security tools that perform code analysis on client-
side applications. These analyzers can typically test for JavaScript security vulnerabilities, issues
in implementation, configuration errors and other risks that can be exploited by attackers. The
Veracode platform provides JavaScript security analysis through its automated cloud-based
service. Veracode assesses web applications and client-side technologies in a running
environment in order to discover JavaScript security vulnerabilities and other issues.

JavaScript is designed as an open scripting language. It is not intended to replace proper security
measures, and should never be used in place of proper encryption. See also my article
about cross site scripting.

JavaScript has its own security model, but this is not designed to protect the Web site owner or
the data passed between the browser and the server. The security model is designed to protect the
user from malicious Web sites, and as a result, it enforces strict limits on what the page author is

5|Page VAPM ALMALA


September
MR.SWAMI R.S. {MOBILE NO:- +91-8275265361}
17, 2019

allowed to do. They may have control over their own page inside the browser, but that is where
their abilities end.

 JavaScripts cannot read or write files on users' computers (File API - not currently supported
by many browsers - allows files to be read by scripts if the user specifically chooses to allow
it), though they can cause the browser to load remote pages and resources like scripts or
images, which the browser may choose to cache locally. They cannot create files on the
server (except by communicating with a server side script that creates files for them). The
only thing they can store on the user's computer are cookies (and Web Storage - similar to
cookies but with more data types - in newer browsers).
 They are allowed to interact with other pages in a frameset, if those frames originate from the
same Web site, but not if they originate from another Web site (the postMessage method
from HTML 5 does safely extend this capability, but I will not cover that here). Some
browsers will even treat different port numbers on the same server as a different Web site.
 JavaScript cannot be used to set the value attribute of a file input, and will not be allowed to
use them to upload files without permission.
 JavaScript cannot read what locations a user has visited by reading them from the location
object, although it can tell the browser to jump back or forward any number of steps through
the browser history. It cannot see what other Web pages the user has open.
 JavaScript cannot access the cookies or variables from other sites.
 It cannot see when the user interacts with other programs, or other parts of the browser
window.
 It cannot open windows out of sight from the user or too small for the user to see, and in
most browsers, it cannot close windows that it did not open.

Some other methods:

 window.open() - open a new window


 window.close() - close the current window
 window.moveTo() - move the current window
 window.resizeTo() - resize the current window

<html>
<body>

<button onclick="openWin()">Open "myWindow"</button>


<button onclick="closeWin()">Close "myWindow"</button>

6|Page VAPM ALMALA


September
MR.SWAMI R.S. {MOBILE NO:- +91-8275265361}
17, 2019

<script>
var myWindow;

function openWin() {
myWindow = window.open("", "myWindow", "width=200,height=100");
myWindow.document.write("<p>This is 'myWindow'</p>");
//myWindow.opener.document.write("<p>This is the source window!</p>");
}

function closeWin() {
myWindow.close();
}
</script>

</body>
</html>

<!DOCTYPE html>
<html>
<head>
<script>
function scrollWindow() {
window.scrollTo(0, 100);
}
</script>
</head>
<body>

<input type="button" onclick="scrollWindow()" value="Scroll" />

<h2>Reserved Words</h2>
<hr>
<p>You cannot use reserved words as variables, labels, or function names:</p>
<hr>
<br>
abstract<br><br>
arguments<br><br>
boolean<br><br>
break<br><br>
byte<br><br>
case<br><br>
catch<br><br>
char<br><br>
class<br><br>
const<br><br>

7|Page VAPM ALMALA


September
MR.SWAMI R.S. {MOBILE NO:- +91-8275265361}
17, 2019

continue<br><br>
debugger<br><br>
default<br><br>
delete<br><br>
do<br><br>
double<br><br>
else<br><br>
enum<br><br>
eval<br><br>
export<br><br>
extends<br><br>
false<br><br>
final<br><br>
finally<br><br>
float<br><br>
for<br><br>
function<br><br>
goto<br><br>
if<br><br>
implements<br><br>
import<br><br>
in<br><br>
instanceof<br><br>
int<br><br>
interface<br><br>
let<br><br>
long<br><br>
native<br><br>
new<br><br>
null<br><br>
package<br><br>
private<br><br>
protected<br><br>
public<br><br>
return<br><br>
short<br><br>
static<br><br>
super<br><br>
switch<br><br>
synchronized<br><br>
this<br><br>
throw<br><br>
throws<br><br>
transient<br><br>
true<br><br>
try<br><br>

8|Page VAPM ALMALA


September
MR.SWAMI R.S. {MOBILE NO:- +91-8275265361}
17, 2019

typeof<br><br>
var<br><br>
void<br><br>
volatile<br><br>
while<br><br>
with<br><br>
yield<br><br>

</body>
</html>

Timing Events
The window object allows execution of code at specified time intervals.

These time intervals are called timing events.

The two key methods to use with JavaScript are:

 setTimeout(function, milliseconds)
Executes a function, after waiting a specified number of milliseconds.

 setInterval(function, milliseconds)
Same as setTimeout(), but repeats the execution of the function
continuously.

The setTimeout() and setInterval() are both methods of the HTML DOM
Window object.

The setTimeout() Method


window.setTimeout(function, milliseconds);

The window.setTimeout() method can be written without the window prefix.

The first parameter is a function to be executed.

The second parameter indicates the number of milliseconds before execution.

9|Page VAPM ALMALA


September
MR.SWAMI R.S. {MOBILE NO:- +91-8275265361}
17, 2019

How to Stop the Execution?


The clearTimeout() method stops the execution of the function specified in
setTimeout().

window.clearTimeout(timeoutVariable)

The window.clearTimeout() method can be written without the window prefix.

The clearTimeout() method uses the variable returned from setTimeout():

myVar = setTimeout(function, milliseconds);


clearTimeout(myVar);

If the function has not already been executed, you can stop the execution by
calling the clearTimeout() method:

Example
Same example as above, but with an added "Stop" button:

<button onclick="myVar = setTimeout(myFunction, 3000)">Try it</button>

<button onclick="clearTimeout(myVar)">Stop it</button>

The setInterval() Method


The setInterval() method repeats a given function at every given time-
interval.

window.setInterval(function, milliseconds);

The window.setInterval() method can be written without the window prefix.

The first parameter is the function to be executed.

The second parameter indicates the length of the time-interval between each
execution.

This example executes a function called "myTimer" once every second (like a
digital watch).

10 | P a g e VAPM ALMALA
September
MR.SWAMI R.S. {MOBILE NO:- +91-8275265361}
17, 2019

Example
Display the current time:

var myVar = setInterval(myTimer, 1000);

function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}

How to Stop the Execution?


The clearInterval() method stops the executions of the function specified in
the setInterval() method.

window.clearInterval(timerVariable)

The window.clearInterval() method can be written without the window


prefix.

The clearInterval() method uses the variable returned from setInterval():

myVar = setInterval(function, milliseconds);


clearInterval(myVar);

Example
Same example as above, but we have added a "Stop time" button:

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

<button onclick="clearInterval(myVar)">Stop time</button>

<script>
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>

11 | P a g e VAPM ALMALA
September
MR.SWAMI R.S. {MOBILE NO:- +91-8275265361}
17, 2019

12 | P a g e VAPM ALMALA

You might also like