[Go to site: main page, start]

0% found this document useful (0 votes)
10 views66 pages

Java Script

The document explains various control statements in JavaScript, including if, if...else, if...else if, switch-case, and different types of loops (while, do...while, for, for...in). It provides syntax, examples, and outputs for each statement and loop type, illustrating how they can be used to control the flow of a program based on conditions. Additionally, it covers loop control statements like break and continue to manage loop execution effectively.

Uploaded by

Pooja Singh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views66 pages

Java Script

The document explains various control statements in JavaScript, including if, if...else, if...else if, switch-case, and different types of loops (while, do...while, for, for...in). It provides syntax, examples, and outputs for each statement and loop type, illustrating how they can be used to control the flow of a program based on conditions. Additionally, it covers loop control statements like break and continue to manage loop execution effectively.

Uploaded by

Pooja Singh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript - if...

else Statement
While writing a program, there may be a situation when you need to adopt one out
of a given set of paths. In such cases, you need to use conditional statements that
allow your program to make correct decisions and perform right actions.
JavaScript supports conditional statements which are used to perform different
actions based on different conditions. Here we will explain the if..else statement.

Flow Chart of if-else


The following flow chart shows how the if-else statement works.

JavaScript supports the following forms of if..else statement −

 if statement
 if...else statement
 if...else if... statement.

if statement
The if statement is the fundamental control statement that allows JavaScript to
make decisions and execute statements conditionally.

Syntax
The syntax for a basic if statement is as follows −
if (expression) {
Statement(s) to be executed if expression is true
}
Here a JavaScript expression is evaluated. If the resulting value is true, the given
statement(s) are executed. If the expression is false, then no statement would be
not executed. Most of the times, you will use comparison operators while making
decisions.

Example
Try the following example to understand how the if statement works.
Live Demo

<html>
<body>
<script type = "text/javascript">
<!--
var age = 20;

if( age > 18 ) {


[Link]("<b>Qualifies for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Output
Qualifies for driving
Set the variable to different value and then try...

if...else statement
The 'if...else' statement is the next form of control statement that allows JavaScript
to execute statements in a more controlled way.

Syntax
if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}
Here JavaScript expression is evaluated. If the resulting value is true, the given
statement(s) in the ‘if’ block, are executed. If the expression is false, then the given
statement(s) in the else block are executed.

Example
Try the following code to learn how to implement an if-else statement in JavaScript.
Live Demo

<html>
<body>
<script type = "text/javascript">
<!--
var age = 15;

if( age > 18 )


{
[Link]("<b>Qualifies for driving</b>");
}
else
{
[Link]("<b>Does not qualify for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Output
Does not qualify for driving
Set the variable to different value and then try...

if...else if... statement


The if...else if... statement is an advanced form of if…else that allows JavaScript to
make a correct decision out of several conditions.

Syntax
The syntax of an if-else-if statement is as follows −
if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}
There is nothing special about this code. It is just a series of if statements, where
each if is a part of the else clause of the previous statement. Statement(s) are
executed based on the true condition, if none of the conditions is true, then
the else block is executed.

Example
Try the following code to learn how to implement an if-else-if statement in
JavaScript.
Live Demo

<html>
<body>
<script type = "text/javascript">
<!--
var book = "maths";
if( book == "history" )
{ [Link]("<b>History Book</b>");
}
else if( book == "maths" )
{ [Link]("<b>Maths Book</b>");
}
else if( book == "economics" )
{ [Link]("<b>Economics Book</b>");
}
else
{ [Link]("<b>Unknown Book</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
<html>

Output
Maths Book
Set the variable to different value and then try...
JavaScript - Switch Case
You can use multiple if...else…if statements, as in the previous chapter, to perform a
multiway branch. However, this is not always the best solution, especially when all
of the branches depend on the value of a single variable.
Starting with JavaScript 1.2, you can use a switch statement which handles exactly
this situation, and it does so more efficiently than repeated if...else if statements.

Flow Chart
The following flow chart explains a switch-case statement works.
Syntax
The objective of a switch statement is to give an expression to evaluate and several
different statements to execute based on the value of the expression. The
interpreter checks each case against the value of the expression until a match is
found. If nothing matches, a default condition will be used.
switch (expression) {
case condition 1: statement(s)
break;

case condition 2: statement(s)


break;
...

case condition n: statement(s)


break;

default: statement(s)
}
The break statements indicate the end of a particular case. If they were omitted, the
interpreter would continue executing each statement in each of the following cases.
We will explain break statement in Loop Control chapter.

Example
Try the following example to implement switch-case statement.
Live Demo

<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
[Link]("Entering switch block<br />");
switch (grade) {
case 'A': [Link]("Good job<br />");
break;

case 'B': [Link]("Pretty good<br />");


break;

case 'C': [Link]("Passed<br />");


break;

case 'D': [Link]("Not so good<br />");


break;

case 'F': [Link]("Failed<br />");


break;

default: [Link]("Unknown grade<br />")


}
[Link]("Exiting switch block");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Output
Entering switch block
Good job
Exiting switch block
Set the variable to different value and then try...
Break statements play a major role in switch-case statements. Try the following
code that uses switch-case statement without any break statement.
Live Demo

<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
[Link]("Entering switch block<br />");
switch (grade) {
case 'A': [Link]("Good job<br />");
case 'B': [Link]("Pretty good<br />");
case 'C': [Link]("Passed<br />");
case 'D': [Link]("Not so good<br />");
case 'F': [Link]("Failed<br />");
default: [Link]("Unknown grade<br />")
}
[Link]("Exiting switch block");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Output
Entering switch block
Good job
Pretty good
Passed
Not so good
Failed
Unknown grade
Exiting switch block
Set the variable to different value and then try...
JavaScript - Loops
While writing a program, you may encounter a situation where you need to perform
an action over and over again. In such situations, you would need to write loop
statements to reduce the number of lines.
JavaScript supports all the necessary loops to ease down the pressure of
programming.

The while Loop


The most basic loop in JavaScript is the while loop which would be discussed in this
chapter. The purpose of a while loop is to execute a statement or code block
repeatedly as long as an expression is true. Once the expression
becomes false, the loop terminates.

Flow Chart
The flow chart of while loop looks as follows −
Syntax
The syntax of while loop in JavaScript is as follows −
while (expression) {
Statement(s) to be executed if expression is true
}
Example
Try the following example to implement while loop.
Live Demo

<html>
<body>

<script type = "text/javascript">


<!--
var count = 0;
[Link]("Starting Loop ");

while (count < 10) {


[Link]("Current Count : " + count + "<br />");
count++;
}

[Link]("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...

The do...while Loop


The do...while loop is similar to the while loop except that the condition check
happens at the end of the loop. This means that the loop will always be executed at
least once, even if the condition is false.

Flow Chart
The flow chart of a do-while loop would be as follows −

Syntax
The syntax for do-while loop in JavaScript is as follows −
do {
Statement(s) to be executed;
} while (expression);
Note − Don’t miss the semicolon used at the end of the do...while loop.

Example
Try the following example to learn how to implement a do-while loop in JavaScript.
Live Demo

<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;

[Link]("Starting Loop" + "<br />");


do {
[Link]("Current Count : " + count + "<br />");
count++;
}

while (count < 5);


[Link] ("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Loop Stopped!
Set the variable to different value and then try...
JavaScript - For Loop
The 'for' loop is the most compact form of looping. It includes the following three
important parts −

 The loop initialization where we initialize our counter to a starting


value. The initialization statement is executed before the loop begins.
 The test statement which will test if a given condition is true or not. If
the condition is true, then the code given inside the loop will be
executed, otherwise the control will come out of the loop.
 The iteration statement where you can increase or decrease your
counter.
You can put all the three parts in a single line separated by semicolons.

Flow Chart
The flow chart of a for loop in JavaScript would be as follows −

Syntax
The syntax of for loop is JavaScript is as follows −
for (initialization; test condition; iteration statement) {
Statement(s) to be executed if test condition is true
}
Example
Try the following example to learn how a for loop works in JavaScript.
Live Demo

<html>
<body>
<script type = "text/javascript">
<!--
var count;
[Link]("Starting Loop" + "<br />");

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


[Link]("Current Count : " + count );
[Link]("<br />");
}
[Link]("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...
JavaScript for...in loop
The for...in loop is used to loop through an object's properties. As we have not
discussed Objects yet, you may not feel comfortable with this loop. But once you
understand how objects behave in JavaScript, you will find this loop very useful.

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

Example
Try the following example to implement ‘for-in’ loop. It prints the web
browser’s Navigator object.
Live Demo

<html>
<body>
<script type = "text/javascript">
<!--
var aProperty;
[Link]("Navigator Object Properties<br /> ");
for (aProperty in navigator) {
[Link](aProperty);
[Link]("<br />");
}
[Link] ("Exiting from the loop!");
//-->
</script>
<p>Set the variable to different object and then try...</p>
</body>
</html>

Output
Navigator Object Properties
serviceWorker
webkitPersistentStorage
webkitTemporaryStorage
geolocation
doNotTrack
onLine
languages
language
userAgent
product
platform
appVersion
appName
appCodeName
hardwareConcurrency
maxTouchPoints
vendorSub
vendor
productSub
cookieEnabled
mimeTypes
plugins
javaEnabled
getStorageUpdates
getGamepads
webkitGetUserMedia
vibrate
getBattery
sendBeacon
registerProtocolHandler
unregisterProtocolHandler
Exiting from the loop!
Set the variable to different object and then try...
JavaScript - Loop Control
JavaScript provides full control to handle loops and switch statements. There may
be a situation when you need to come out of a loop without reaching its bottom.
There may also be a situation when you want to skip a part of your code block and
start the next iteration of the loop.
To handle all such situations, JavaScript provides break and continue statements.
These statements are used to immediately come out of any loop or to start the next
iteration of any loop respectively.

The break Statement


The break statement, which was briefly introduced with the switch statement, is
used to exit a loop early, breaking out of the enclosing curly braces.

Flow Chart
The flow chart of a break statement would look as follows −

Example
The following example illustrates the use of a break statement with a while loop.
Notice how the loop breaks out early once x reaches 5 and reaches
to [Link] (..) statement just below to the closing curly brace −
Live Demo

<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
[Link]("Entering the loop<br /> ");

while (x < 20) {


if (x == 5) {
break; // breaks out of loop completely
}
x = x + 1;
[Link]( x + "<br />");
}
[Link]("Exiting the loop!<br /> ");
//-->
</script>

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


</body>
</html>

Output
Entering the loop
2
3
4
5
Exiting the loop!
Set the variable to different value and then try...
We already have seen the usage of break statement inside a switch statement.

The continue Statement


The continue statement tells the interpreter to immediately start the next iteration
of the loop and skip the remaining code block. When a continue statement is
encountered, the program flow moves to the loop check expression immediately
and if the condition remains true, then it starts the next iteration, otherwise the
control comes out of the loop.

Example
This example illustrates the use of a continue statement with a while loop. Notice
how the continue statement is used to skip printing when the index held in
variable x reaches 5 −
Live Demo

<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
[Link]("Entering the loop<br /> ");

while (x < 10) {


x = x + 1;

if (x == 5) {
continue; // skip rest of the loop body
}
[Link]( x + "<br />");
}
[Link]("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Output
Entering the loop
2
3
4
6
7
8
9
10
Exiting the loop!
Set the variable to different value and then try...

Using Labels to Control the Flow


Starting from JavaScript 1.2, a label can be used with break and continue to control
the flow more precisely. A label is simply an identifier followed by a colon (:) that is
applied to a statement or a block of code. We will see two different examples to
understand how to use labels with break and continue.
Note − Line breaks are not allowed between the ‘continue’ or ‘break’ statement
and its label name. Also, there should not be any other statement in between a
label name and associated loop.
Try the following two examples for a better understanding of Labels.

Example 1
The following example shows how to implement Label with a break statement.
Live Demo

<html>
<body>
<script type = "text/javascript">
<!--
[Link]("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 5; i++) {
[Link]("Outerloop: " + i + "<br />");
innerloop:
for (var j = 0; j < 5; j++) {
if (j > 3 ) break ; // Quit the innermost loop
if (i == 2) break innerloop; // Do the same thing
if (i == 4) break outerloop; // Quit the outer loop
[Link]("Innerloop: " + j + " <br />");
}
}
[Link]("Exiting the loop!<br /> ");
//-->
</script>
</body>
</html>

Output
Entering the loop!
Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 2
Outerloop: 3
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 4
Exiting the loop!
Example 2
Live Demo

<html>
<body>

<script type = "text/javascript">


<!--
[Link]("Entering the loop!<br /> ");
outerloop: // This is the label name

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


[Link]("Outerloop: " + i + "<br />");
for (var j = 0; j < 5; j++) {
if (j == 3) {
continue outerloop;
}
[Link]("Innerloop: " + j + "<br />");
}
}
[Link]("Exiting the loop!<br /> ");
//-->
</script>

</body>
</html>

Output
Entering the loop!
Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 2
Innerloop: 0
Innerloop: 1
Innerloop: 2
Exiting the loop!
JavaScript - Functions
A function is a group of reusable code which can be called anywhere in your
program. This eliminates the need of writing the same code again and again. It
helps programmers in writing modular codes. Functions allow a programmer to
divide a big program into a number of small and manageable functions.
Like any other advanced programming language, JavaScript also supports all the
features necessary to write modular code using functions. You must have seen
functions like alert() and write() in the earlier chapters. We were using these
functions again and again, but they had been written in core JavaScript only once.
JavaScript allows us to write our own functions as well. This section explains how
to write your own functions in JavaScript.

Function Definition
Before we use a function, we need to define it. The most common way to define a
function in JavaScript is by using the function keyword, followed by a unique
function name, a list of parameters (that might be empty), and a statement block
surrounded by curly braces.

Syntax
The basic syntax is shown here.
<script type = "text/javascript">
<!--
function functionname(parameter-list) {
statements
}
//-->
</script>
Example
Try the following example. It defines a function called sayHello that takes no
parameters −

<script type = "text/javascript">


<!--
function sayHello() {
alert("Hello there");
}
//-->
</script>

Calling a Function
To invoke a function somewhere later in the script, you would simply need to write
the name of that function as shown in the following code.
Live Demo

<html>
<head>
<script type = "text/javascript">
function sayHello() {
[Link] ("Hello there!");
}
</script>

</head>

<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" value = "Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>

Output

Function Parameters
Till now, we have seen functions without parameters. But there is a facility to pass
different parameters while calling a function. These passed parameters can be
captured inside the function and any manipulation can be done over those
parameters. A function can take multiple parameters separated by comma.

Example
Try the following example. We have modified our sayHello function here. Now it
takes two parameters.
Live Demo

<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
[Link] (name + " is " + age + " years old.");
}
</script>
</head>

<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" 7)" value = "Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>

Output

The return Statement


A JavaScript function can have an optional return statement. This is required if you
want to return a value from a function. This statement should be the last statement
in a function.
For example, you can pass two numbers in a function and then you can expect the
function to return their multiplication in your calling program.

Example
Try the following example. It defines a function that takes two parameters and
concatenates them before returning the resultant in the calling program.
Live Demo

<html>
<head>
<script type = "text/javascript">
function concatenate(first, last) {
var full;
full = first + last;
return full;
}
function secondFunction() {
var result;
result = concatenate('Zara', 'Ali');
[Link] (result );
}
</script>
</head>

<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" value = "Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>

Output
There is a lot to learn about JavaScript functions, however we have covered the
most important concepts in this tutorial.

 JavaScript Nested Functions


 JavaScript Function( ) Constructor
 JavaScript Function Literals
JavaScript - Events
What is an Event ?
JavaScript's interaction with HTML is handled through events that occur when the
user or the browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click
too is an event. Other examples include events like pressing any key, closing a
window, resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which
cause buttons to close windows, messages to be displayed to users, data to be
validated, and virtually any other type of response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML
element contains a set of events which can trigger JavaScript Code.
Please go through this small tutorial for a better understanding HTML Event
Reference. Here we will see a few examples to understand a relation between
Event and JavaScript −

onclick Event Type


This is the most frequently used event type which occurs when a user clicks the left
button of his mouse. You can put your validation, warning etc., against this event
type.

Example
Try the following example.
Live Demo

<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>

<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" value = "Say Hello" />
</form>
</body>
</html>

Output

onsubmit Event Type


onsubmit is an event that occurs when you try to submit a form. You can put your
form validation against this event type.

Example
The following example shows how to use onsubmit. Here we are calling
a validate() function before submitting a form data to the webserver.
If validate() function returns true, the form will be submitted, otherwise it will not
submit the data.
Try the following example.
<html>
<head>
<script type = "text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>

<body>
<form method = "POST" action = "[Link]" validation()">
.......
<input type = "submit" value = "Submit" />
</form>
</body>
</html>

onmouseover and onmouseout


These two event types will help you create nice effects with images or even with
text as well. The onmouseover event triggers when you bring your mouse over any
element and the onmouseout triggers when you move your mouse out from that
element. Try the following example.
Live Demo

<html>
<head>
<script type = "text/javascript">
<!--
function over() {
[Link] ("Mouse Over");
}
function out() {
[Link] ("Mouse Out");
}
//-->
</script>
</head>

<body>
<p>Bring your mouse inside the division to see the result:</p>
<div > <h2> This is inside the division </h2>
</div>
</body>
</html>

Output

HTML 5 Standard Events


The standard HTML 5 events are listed here for your reference. Here script indicates
a Javascript function to be executed against that event.

Attribute Value Description

Offline script Triggers when the document goes offline

Onabort script Triggers on an abort event

Onafterprint script Triggers after the document is printed

onbeforeonload script Triggers before the document loads

Onbeforeprint script Triggers before the document is printed

Onblur script Triggers when the window loses focus

Triggers when media can start play, but might has to stop
Oncanplay script
for buffering

Triggers when media can be played to the end, without


oncanplaythrough script
stopping for buffering

Onchange script Triggers when an element changes

Onclick script Triggers on a mouse click

oncontextmenu script Triggers when a context menu is triggered

Ondblclick script Triggers on a mouse double-click

Ondrag script Triggers when an element is dragged

Ondragend script Triggers at the end of a drag operation

Triggers when an element has been dragged to a valid


Ondragenter script
drop target

Ondragleave script Triggers when an element is being dragged over a valid


drop target

Ondragover script Triggers at the start of a drag operation

Ondragstart script Triggers at the start of a drag operation

Ondrop script Triggers when dragged element is being dropped

ondurationchange script Triggers when the length of the media is changed

Triggers when a media resource element suddenly


Onemptied script
becomes empty.

Onended script Triggers when media has reach the end

Onerror script Triggers when an error occur

Onfocus script Triggers when the window gets focus

Onformchange script Triggers when a form changes

Onforminput script Triggers when a form gets user input

Onhaschange script Triggers when the document has change

Oninput script Triggers when an element gets user input

Oninvalid script Triggers when an element is invalid

Onkeydown script Triggers when a key is pressed

Onkeypress script Triggers when a key is pressed and released

Onkeyup script Triggers when a key is released

Onload script Triggers when the document loads

Onloadeddata script Triggers when media data is loaded

Triggers when the duration and other media data of a


onloadedmetadata script
media element is loaded

Onloadstart script Triggers when the browser starts to load the media data

Onmessage script Triggers when the message is triggered

Onmousedown script Triggers when a mouse button is pressed


Onmousemove script Triggers when the mouse pointer moves

Onmouseout script Triggers when the mouse pointer moves out of an element

Onmouseover script Triggers when the mouse pointer moves over an element

Onmouseup script Triggers when a mouse button is released

onmousewheel script Triggers when the mouse wheel is being rotated

Onoffline script Triggers when the document goes offline

Onoine script Triggers when the document comes online

Ononline script Triggers when the document comes online

Onpagehide script Triggers when the window is hidden

Onpageshow script Triggers when the window becomes visible

Onpause script Triggers when media data is paused

Onplay script Triggers when media data is going to start playing

Onplaying script Triggers when media data has start playing

Onpopstate script Triggers when the window's history changes

Onprogress script Triggers when the browser is fetching the media data

Onratechange script Triggers when the media data's playing rate has changed

onreadystatechange script Triggers when the ready-state changes

Onredo script Triggers when the document performs a redo

Onresize script Triggers when the window is resized

Onscroll script Triggers when an element's scrollbar is being scrolled

Triggers when a media element's seeking attribute is no


Onseeked script
longer true, and the seeking has ended

Triggers when a media element's seeking attribute is true,


Onseeking script
and the seeking has begun

Onselect script Triggers when an element is selected


Onstalled script Triggers when there is an error in fetching media data

Onstorage script Triggers when a document loads

Onsubmit script Triggers when a form is submitted

Triggers when the browser has been fetching media data,


Onsuspend script
but stopped before the entire media file was fetched

Ontimeupdate script Triggers when media changes its playing position

Onundo script Triggers when a document performs an undo

Onunload script Triggers when the user leaves the document

Triggers when media changes the volume, also when


onvolumechange script
volume is set to "mute"

Triggers when media has stopped playing, but is expected


Onwaiting script
to resume

JavaScript - Dialog Boxes


JavaScript supports three important types of dialog boxes. These dialog boxes can be used to
raise and alert, or to get confirmation on any input or to have a kind of input from the users.
Here we will discuss each dialog box one by one.

Alert Dialog Box


An alert dialog box is mostly used to give a warning message to the users. For example, if
one input field requires to enter some text but the user does not provide any input, then as a
part of validation, you can use an alert box to give a warning message.
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one
button "OK" to select and proceed.
Example
Live Demo

<html>
<head>
<script type = "text/javascript">
<!--
function Warn() {
alert ("This is a warning message!");
[Link] ("This is a warning message!");
}
//-->
</script>
</head>

<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" />
</form>
</body>
</html>

Output

Confirmation Dialog Box


A confirmation dialog box is mostly used to take user's consent on any option. It displays a
dialog box with two buttons: OK and Cancel.
If the user clicks on the OK button, the window method confirm() will return true. If the user
clicks on the Cancel button, then confirm() returns false. You can use a confirmation dialog
box as follows.
Example
Live Demo

<html>
<head>
<script type = "text/javascript">
<!--
function getConfirmation() {
var retVal = confirm("Do you want to continue ?");
if( retVal == true ) {
[Link] ("User wants to continue!");
return true;
} else {
[Link] ("User does not want to continue!");
return false;
}
}
//-->
</script>
</head>

<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" />
</form>
</body>
</html>

Output

Prompt Dialog Box


The prompt dialog box is very useful when you want to pop-up a text box to get user input.
Thus, it enables you to interact with the user. The user needs to fill in the field and then click
OK.
This dialog box is displayed using a method called prompt() which takes two parameters: (i)
a label which you want to display in the text box and (ii) a default string to display in the text
box.
This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the
window method prompt() will return the entered value from the text box. If the user clicks
the Cancel button, the window method prompt() returns null.
Example
The following example shows how to use a prompt dialog box −
Live Demo

<html>
<head>
<script type = "text/javascript">
<!--
function getValue() {
var retVal = prompt("Enter your name : ", "your name here");
[Link]("You have entered : " + retVal);
}
//-->
</script>
</head>

<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" />
</form>
</body>
</html>

Output
JavaScript - Void Keyword
void is an important keyword in JavaScript which can be used as a unary operator that
appears before its single operand, which may be of any type. This operator specifies an
expression to be evaluated without returning a value.

Syntax
The syntax of void can be either of the following two −
<head>
<script type = "text/javascript">
<!--
void func()
javascript:void func()
or:
void(func())
javascript:void(func())
//-->
</script>
</head>
Example 1
The most common use of this operator is in a client-side javascript: URL, where it allows
you to evaluate an expression for its side-effects without the browser displaying the value of
the evaluated expression.
Here the expression alert ('Warning!!!') is evaluated but it is not loaded back into the
current document −
Live Demo

<html>
<head>
<script type = "text/javascript">
<!--
//-->
</script>
</head>

<body>
<p>Click the following, This won't react at all...</p>
<a href = "javascript:void(alert('Warning!!!'))">Click me!</a>
</body>
</html>

Output
Example 2
Take a look at the following example. The following link does nothing because the
expression "0" has no effect in JavaScript. Here the expression "0" is evaluated, but it is not
loaded back into the current document.
Live Demo
<html>
<head>
<script type = "text/javascript">
<!--
//-->
</script>
</head>

<body>
<p>Click the following, This won't react at all...</p>
<a href = "javascript:void(0)">Click me!</a>
</body>
</html>

Output
Example 3
Another use of void is to purposely generate the undefined value as follows.
Live Demo

<html>
<head>
<script type = "text/javascript">
<!--
function getValue() {
var a,b,c;

a = void ( b = 5, c = 7 );
[Link]('a = ' + a + ' b = ' + b +' c = ' + c );
}
//-->
</script>
</head>

<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" />
</form>
</body>
</html>

Output
JavaScript - Page Printing
Many times you would like to place a button on your webpage to print the content of that web
page via an actual printer. JavaScript helps you to implement this functionality using
the print function of window object.
The JavaScript print function [Link]() prints the current web page when executed.
You can call this function directly using the onclick event as shown in the following
example.
Example
Try the following example.
Live Demo

<html>
<head>
<script type = "text/javascript">
<!--
//-->
</script>
</head>

<body>
<form>
<input type = "button" value = "Print" />
</form>
</body>
<html>

Output
Although it serves the purpose of getting a printout, it is not a recommended way. A printer
friendly page is really just a page with text, no images, graphics, or advertising.
You can make a page printer friendly in the following ways −
 Make a copy of the page and leave out unwanted text and graphics, then link to
that printer friendly page from the original. Check Example.
 If you do not want to keep an extra copy of a page, then you can mark your
printable text using proper comments like <!-- PRINT STARTS HERE -->.....
<!-- PRINT ENDS HERE --> and then you can use PERL or any other script
in the background to purge printable text and display for final printing. We at
Tutorialspoint use this method to provide print facility to our site visitors.

How to Print a Page?


If you don’t find the above facilities on a web page, then you can use the browser's standard
toolbar to get print the web page. Follow the link as follows.
File → Print → Click OK button.
JavaScript - Objects Overview
JavaScript is an Object Oriented Programming (OOP) language. A programming language
can be called object-oriented if it provides four basic capabilities to developers −
 Encapsulation − the capability to store related information, whether data or
methods, together in an object.
 Aggregation − the capability to store one object inside another object.
 Inheritance − the capability of a class to rely upon another class (or number of
classes) for some of its properties and methods.
 Polymorphism − the capability to write one function or method that works in
a variety of different ways.
Objects are composed of attributes. If an attribute contains a function, it is considered to be a
method of the object, otherwise the attribute is considered a property.

Object Properties
Object properties can be any of the three primitive data types, or any of the abstract data
types, such as another object. Object properties are usually variables that are used internally
in the object's methods, but can also be globally visible variables that are used throughout the
page.
The syntax for adding a property to an object is −
[Link] = propertyValue;
For example − The following code gets the document title using the "title" property of
the document object.
var str = [Link];

Object Methods
Methods are the functions that let the object do something or let something be done to it.
There is a small difference between a function and a method – at a function is a standalone
unit of statements and a method is attached to an object and can be referenced by
the this keyword.
Methods are useful for everything from displaying the contents of the object to the screen to
performing complex mathematical operations on a group of local properties and parameters.
For example − Following is a simple example to show how to use the write() method of
document object to write any content on the document.
[Link]("This is test");

User-Defined Objects
All user-defined objects and built-in objects are descendants of an object called Object.
The new Operator
The new operato

r is used to create an instance of an object. To create an object, the new operator is followed
by the constructor method.
In the following example, the constructor methods are Object(), Array(), and Date(). These
constructors are built-in JavaScript functions.
var employee = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("August 15, 1947");

The Object() Constructor


A constructor is a function that creates and initializes an object. JavaScript provides a special
constructor function called Object() to build the object. The return value of
the Object() constructor is assigned to a variable.
The variable contains a reference to the new object. The properties assigned to the object are
not variables and are not defined with the var keyword.
Example 1
Try the following example; it demonstrates how to create an Object.
Live Demo

<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
var book = new Object(); // Create the object
[Link] = "Perl"; // Assign properties to the object
[Link] = "Mohtashim";
</script>
</head>

<body>
<script type = "text/javascript">
[Link]("Book name is : " + [Link] + "<br>");
[Link]("Book author is : " + [Link] + "<br>");
</script>
</body>
</html>

Output
Book name is : Perl
Book author is : Mohtashim
Example 2
This example demonstrates how to create an object with a User-Defined Function.
Here this keyword is used to refer to the object that has been passed to a function.
Live Demo

<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
function book(title, author) {
[Link] = title;
[Link] = author;
}
</script>
</head>

<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
[Link]("Book title is : " + [Link] + "<br>");
[Link]("Book author is : " + [Link] + "<br>");
</script>
</body>
</html>

Output
Book title is : Perl
Book author is : Mohtashim

Defining Methods for an Object


The previous examples demonstrate how the constructor creates the object and assigns
properties. But we need to complete the definition of an object by assigning methods to it.
Example
Try the following example; it shows how to add a function along with an object.
Live Demo

<html>

<head>
<title>User-defined objects</title>
<script type = "text/javascript">
// Define a function which will work as a method
function addPrice(amount) {
[Link] = amount;
}

function book(title, author) {


[Link] = title;
[Link] = author;
[Link] = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
[Link](100);

[Link]("Book title is : " + [Link] + "<br>");


[Link]("Book author is : " + [Link] + "<br>");
[Link]("Book price is : " + [Link] + "<br>");
</script>
</body>
</html>

Output
Book title is : Perl
Book author is : Mohtashim
Book price is : 100

The 'with' Keyword


The ‘with’ keyword is used as a kind of shorthand for referencing an object's properties or
methods.
The object specified as an argument to with becomes the default object for the duration of the
block that follows. The properties and methods for the object can be used without naming the
object.
Syntax
The syntax for with object is as follows −
with (object) {
properties used without the object name and dot
}
Example
Try the following example.
Live Demo

<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
// Define a function which will work as a method
function addPrice(amount) {
with(this) {
price = amount;
}
}
function book(title, author) {
[Link] = title;
[Link] = author;
[Link] = 0;
[Link] = addPrice; // Assign that method as property.
}
</script>
</head>

<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
[Link](100);

[Link]("Book title is : " + [Link] + "<br>");


[Link]("Book author is : " + [Link] + "<br>");
[Link]("Book price is : " + [Link] + "<br>");
</script>
</body>
</html>

Output
Book title is : Perl
Book author is : Mohtashim
Book price is : 100

JavaScript Native Objects


JavaScript has several built-in or native objects. These objects are accessible anywhere in
your program and will work the same way in any browser running in any operating system.
Here is the list of all important JavaScript Native Objects −
 JavaScript Number Object
 JavaScript Boolean Object
 JavaScript String Object
 JavaScript Array Object
 JavaScript Date Object
 JavaScript Math Object
 JavaScript RegExp Object
JavaScript - The Number Object
The Number object represents numerical date, either integers or floating-point numbers. In
general, you do not need to worry about Number objects because the browser automatically
converts number literals to instances of the number class.
Syntax
The syntax for creating a number object is as follows −
var val = new Number(number);
In the place of number, if you provide any non-number argument, then the argument cannot
be converted into a number, it returns NaN (Not-a-Number).

Number Properties
Here is a list of each property and their description.

[Link]. Property & Description

1 MAX_VALUE
The largest possible value a number in JavaScript can have 1.7976931348623157E+308

2 MIN_VALUE
The smallest possible value a number in JavaScript can have 5E-324

3 NaN
Equal to a value that is not a number.

4 NEGATIVE_INFINITY
A value that is less than MIN_VALUE.

5 POSITIVE_INFINITY
A value that is greater than MAX_VALUE

6 prototype
A static property of the Number object. Use the prototype property to assign new
properties and methods to the Number object in the current document

7 constructor
Returns the function that created this object's instance. By default this is the Number
object.

In the following sections, we will take a few examples to demonstrate the properties of
Number.

Number Methods
The Number object contains only the default methods that are a part of every object's
definition.

[Link]. Method & Description

1 toExponential()
Forces a number to display in exponential notation, even if the number is in the range in
which JavaScript normally uses standard notation.

2 toFixed()
Formats a number with a specific number of digits to the right of the decimal.

3 toLocaleString()
Returns a string value version of the current number in a format that may vary
according to a browser's local settings.

4 toPrecision()
Defines how many total digits (including digits to the left and right of the decimal) to
display of a number.

5 toString()
Returns the string representation of the number's value.

6 valueOf()
Returns the number's value.

In the following sections, we will have a few examples to explain the methods of Number.

JavaScript - The Boolean Object


The Boolean object represents two values, either "true" or "false". If value parameter is
omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an
initial value of false.
Syntax
Use the following syntax to create a boolean object.
var val = new Boolean(value);

Boolean Properties
Here is a list of the properties of Boolean object −

[Link]. Property & Description

1 constructor
Returns a reference to the Boolean function that created the object.

2 prototype
The prototype property allows you to add properties and methods to an object.
In the following sections, we will have a few examples to illustrate the properties of Boolean
object.

Boolean Methods
Here is a list of the methods of Boolean object and their description.

[Link]. Method & Description

1 toSource()
Returns a string containing the source of the Boolean object; you can use this string to
create an equivalent object.

2 toString()
Returns a string of either "true" or "false" depending upon the value of the object.

3 valueOf()
Returns the primitive value of the Boolean object.

In the following sections, we will have a few examples to demonstrate the usage of the
Boolean methods.

JavaScript - The Strings Object


The String object lets you work with a series of characters; it wraps Javascript's string
primitive data type with a number of helper methods.
As JavaScript automatically converts between string primitives and String objects, you can
call any of the helper methods of the String object on a string primitive.
Syntax
Use the following syntax to create a String object −
var val = new String(string);
The String parameter is a series of characters that has been properly encoded.

String Properties
Here is a list of the properties of String object and their description.

[Link]. Property & Description

1 constructor
Returns a reference to the String function that created the object.

2 length
Returns the length of the string.

3 prototype
The prototype property allows you to add properties and methods to an object.

In the following sections, we will have a few examples to demonstrate the usage of String
properties.

String Methods
Here is a list of the methods available in String object along with their description.

[Link]. Method & Description

1 charAt()
Returns the character at the specified index.

2 charCodeAt()
Returns a number indicating the Unicode value of the character at the given index.

3 concat()
Combines the text of two strings and returns a new string.

4 indexOf()
Returns the index within the calling String object of the first occurrence of the specified
value, or -1 if not found.

5 lastIndexOf()
Returns the index within the calling String object of the last occurrence of the specified
value, or -1 if not found.

6 localeCompare()
Returns a number indicating whether a reference string comes before or after or is the
same as the given string in sort order.

7 match()
Used to match a regular expression against a string.

8 replace()
Used to find a match between a regular expression and a string, and to replace the
matched substring with a new substring.
9 search()
Executes the search for a match between a regular expression and a specified string.

10 slice()
Extracts a section of a string and returns a new string.

11 split()
Splits a String object into an array of strings by separating the string into substrings.

12 substr()
Returns the characters in a string beginning at the specified location through the
specified number of characters.

13 substring()
Returns the characters in a string between two indexes into the string.

14 toLocaleLowerCase()
The characters within a string are converted to lower case while respecting the current
locale.

15 toLocaleUpperCase()
The characters within a string are converted to upper case while respecting the current
locale.

16 toLowerCase()
Returns the calling string value converted to lower case.

17 toString()
Returns a string representing the specified object.

18 toUpperCase()
Returns the calling string value converted to uppercase.

19 valueOf()
Returns the primitive value of the specified object.

String HTML Wrappers


Here is a list of the methods that return a copy of the string wrapped inside an appropriate
HTML tag.

[Link]. Method & Description

1 anchor()
Creates an HTML anchor that is used as a hypertext target.

2 big()
Creates a string to be displayed in a big font as if it were in a <big> tag.

3 blink()
Creates a string to blink as if it were in a <blink> tag.

4 bold()
Creates a string to be displayed as bold as if it were in a <b> tag.

5 fixed()
Causes a string to be displayed in fixed-pitch font as if it were in a <tt> tag

6 fontcolor()
Causes a string to be displayed in the specified color as if it were in a <font
color="color"> tag.

7 fontsize()
Causes a string to be displayed in the specified font size as if it were in a <font
size="size"> tag.

8 italics()
Causes a string to be italic, as if it were in an <i> tag.

9 link()
Creates an HTML hypertext link that requests another URL.

10 small()
Causes a string to be displayed in a small font, as if it were in a <small> tag.

11 strike()
Causes a string to be displayed as struck-out text, as if it were in a <strike> tag.
12 sub()
Causes a string to be displayed as a subscript, as if it were in a <sub> tag

13 sup()
Causes a string to be displayed as a superscript, as if it were in a <sup> tag

In the following sections, we will have a few examples to demonstrate the usage of String
methods.

JavaScript - The Arrays Object


The Array object lets you store multiple values in a single variable. It stores a fixed-size
sequential collection of elements of the same type. An array is used to store a collection of
data, but it is often more useful to think of an array as a collection of variables of the same
type.
Syntax
Use the following syntax to create an Array object −
var fruits = new Array( "apple", "orange", "mango" );
The Array parameter is a list of strings or integers. When you specify a single numeric
parameter with the Array constructor, you specify the initial length of the array. The
maximum length allowed for an array is 4,294,967,295.
You can create array by simply assigning values as follows −

var fruits = [ "apple", "orange", "mango" ];

You will use ordinal numbers to access and to set values inside an array as follows.
fruits[0] is the first element
fruits[1] is the second element
fruits[2] is the third element

Array Properties
Here is a list of the properties of the Array object along with their description.

[Link]. Property & Description

1 constructor
Returns a reference to the array function that created the object.

2 index
The property represents the zero-based index of the match in the string
3 input
This property is only present in arrays created by regular expression matches.

4 length
Reflects the number of elements in an array.

5 prototype
The prototype property allows you to add properties and methods to an object.

In the following sections, we will have a few examples to illustrate the usage of Array
properties.

Array Methods
Here is a list of the methods of the Array object along with their description.

[Link]. Method & Description

1 concat()
Returns a new array comprised of this array joined with other array(s) and/or value(s).

2 every()
Returns true if every element in this array satisfies the provided testing function.

3 filter()
Creates a new array with all of the elements of this array for which the provided
filtering function returns true.

4 forEach()
Calls a function for each element in the array.

5 indexOf()
Returns the first (least) index of an element within the array equal to the specified
value, or -1 if none is found.

6 join()
Joins all elements of an array into a string.

7 lastIndexOf()
Returns the last (greatest) index of an element within the array equal to the specified
value, or -1 if none is found.

8 map()
Creates a new array with the results of calling a provided function on every element in
this array.

9 pop()
Removes the last element from an array and returns that element.

10 push()
Adds one or more elements to the end of an array and returns the new length of the
array.

11 reduce()
Apply a function simultaneously against two values of the array (from left-to-right) as
to reduce it to a single value.

12 reduceRight()
Apply a function simultaneously against two values of the array (from right-to-left) as
to reduce it to a single value.

13 reverse()
Reverses the order of the elements of an array -- the first becomes the last, and the last
becomes the first.

14 shift()
Removes the first element from an array and returns that element.

15 slice()
Extracts a section of an array and returns a new array.

16 some()
Returns true if at least one element in this array satisfies the provided testing function.

17 toSource()
Represents the source code of an object

18 sort()
Sorts the elements of an array
19 splice()
Adds and/or removes elements from an array.

20 toString()
Returns a string representing the array and its elements.

21 unshift()
Adds one or more elements to the front of an array and returns the new length of the
array.

In the following sections, we will have a few examples to demonstrate the usage of Array
methods.

JavaScript - The Date Object


The Date object is a datatype built into the JavaScript language. Date objects are created with
the new Date( ) as shown below.
Once a Date object is created, a number of methods allow you to operate on it. Most methods
simply allow you to get and set the year, month, day, hour, minute, second, and millisecond
fields of the object, using either local time or UTC (universal, or GMT) time.
The ECMAScript standard requires the Date object to be able to represent any date and time,
to millisecond precision, within 100 million days before or after 1/1/1970. This is a range of
plus or minus 273,785 years, so JavaScript can represent date and time till the year 275755.
Syntax
You can use any of the following syntaxes to create a Date object using Date() constructor.
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])
Note − Parameters in the brackets are always optional.
Here is a description of the parameters −
 No Argument − With no arguments, the Date() constructor creates a Date
object set to the current date and time.
 milliseconds − When one numeric argument is passed, it is taken as the
internal numeric representation of the date in milliseconds, as returned by the
getTime() method. For example, passing the argument 5000 creates a date that
represents five seconds past midnight on 1/1/70.
 datestring − When one string argument is passed, it is a string representation
of a date, in the format accepted by the [Link]() method.
 7 agruments − To use the last form of the constructor shown above. Here is a
description of each argument −
o year − Integer value representing the year. For compatibility (in
order to avoid the Y2K problem), you should always specify the
year in full; use 1998, rather than 98.
o month − Integer value representing the month, beginning with 0
for January to 11 for December.
o date − Integer value representing the day of the month.
o hour − Integer value representing the hour of the day (24-hour
scale).
o minute − Integer value representing the minute segment of a
time reading.
o second − Integer value representing the second segment of a
time reading.
o millisecond − Integer value representing the millisecond
segment of a time reading.

Date Properties
Here is a list of the properties of the Date object along with their description.

[Link]. Property & Description

1 constructor
Specifies the function that creates an object's prototype.

2 prototype
The prototype property allows you to add properties and methods to an object

In the following sections, we will have a few examples to demonstrate the usage of different
Date properties.

Date Methods
Here is a list of the methods used with Date and their description.

[Link]. Method & Description

1 Date()
Returns today's date and time

2 getDate()
Returns the day of the month for the specified date according to local time.

3 getDay()
Returns the day of the week for the specified date according to local time.
4 getFullYear()
Returns the year of the specified date according to local time.

5 getHours()
Returns the hour in the specified date according to local time.

6 getMilliseconds()
Returns the milliseconds in the specified date according to local time.

7 getMinutes()
Returns the minutes in the specified date according to local time.

8 getMonth()
Returns the month in the specified date according to local time.

9 getSeconds()
Returns the seconds in the specified date according to local time.

10 getTime()
Returns the numeric value of the specified date as the number of milliseconds since
January 1, 1970, 00:00:00 UTC.

11 getTimezoneOffset()
Returns the time-zone offset in minutes for the current locale.

12 getUTCDate()
Returns the day (date) of the month in the specified date according to universal time.

13 getUTCDay()
Returns the day of the week in the specified date according to universal time.

14 getUTCFullYear()
Returns the year in the specified date according to universal time.

15 getUTCHours()
Returns the hours in the specified date according to universal time.

16 getUTCMilliseconds()
Returns the milliseconds in the specified date according to universal time.
17 getUTCMinutes()
Returns the minutes in the specified date according to universal time.

18 getUTCMonth()
Returns the month in the specified date according to universal time.

19 getUTCSeconds()
Returns the seconds in the specified date according to universal time.

20 getYear()
Deprecated - Returns the year in the specified date according to local time. Use
getFullYear instead.

21 setDate()
Sets the day of the month for a specified date according to local time.

22 setFullYear()
Sets the full year for a specified date according to local time.

23 setHours()
Sets the hours for a specified date according to local time.

24 setMilliseconds()
Sets the milliseconds for a specified date according to local time.

25 setMinutes()
Sets the minutes for a specified date according to local time.

26 setMonth()
Sets the month for a specified date according to local time.

27 setSeconds()
Sets the seconds for a specified date according to local time.

28 setTime()
Sets the Date object to the time represented by a number of milliseconds since January
1, 1970, 00:00:00 UTC.
29 setUTCDate()
Sets the day of the month for a specified date according to universal time.

30 setUTCFullYear()
Sets the full year for a specified date according to universal time.

31 setUTCHours()
Sets the hour for a specified date according to universal time.

32 setUTCMilliseconds()
Sets the milliseconds for a specified date according to universal time.

33 setUTCMinutes()
Sets the minutes for a specified date according to universal time.

34 setUTCMonth()
Sets the month for a specified date according to universal time.

35 setUTCSeconds()
Sets the seconds for a specified date according to universal time.

36 setYear()
Deprecated - Sets the year for a specified date according to local time. Use setFullYear
instead.

37 toDateString()
Returns the "date" portion of the Date as a human-readable string.

38 toGMTString()
Deprecated - Converts a date to a string, using the Internet GMT conventions. Use
toUTCString instead.

39 toLocaleDateString()
Returns the "date" portion of the Date as a string, using the current locale's conventions.

40 toLocaleFormat()
Converts a date to a string, using a format string.

41 toLocaleString()
Converts a date to a string, using the current locale's conventions.

42 toLocaleTimeString()
Returns the "time" portion of the Date as a string, using the current locale's
conventions.

43 toSource()
Returns a string representing the source for an equivalent Date object; you can use this
value to create a new object.

44 toString()
Returns a string representing the specified Date object.

45 toTimeString()
Returns the "time" portion of the Date as a human-readable string.

46 toUTCString()
Converts a date to a string, using the universal time convention.

47 valueOf()
Returns the primitive value of a Date object.

Converts a date to a string, using the universal time convention.

Date Static Methods


In addition to the many instance methods listed previously, the Date object also defines two
static methods. These methods are invoked through the Date() constructor itself.

[Link]. Method & Description

1 [Link]( )
Parses a string representation of a date and time and returns the internal millisecond
representation of that date.

2 [Link]( )
Returns the millisecond representation of the specified UTC date and time.

In the following sections, we will have a few examples to demonstrate the usages of Date
Static methods.

JavaScript - The Math Object


The math object provides you properties and methods for mathematical constants and
functions. Unlike other global objects, Math is not a constructor. All the properties and
methods of Math are static and can be called by using Math as an object without creating it.
Thus, you refer to the constant pi as [Link] and you call the sine function as [Link](x),
where x is the method's argument.
Syntax
The syntax to call the properties and methods of Math are as follows
var pi_val = [Link];
var sine_val = [Link](30);

Math Properties
Here is a list of all the properties of Math and their description.

[Link]. Property & Description

1 E\
Euler's constant and the base of natural logarithms, approximately 2.718.

2 LN2
Natural logarithm of 2, approximately 0.693.

3 LN10
Natural logarithm of 10, approximately 2.302.

4 LOG2E
Base 2 logarithm of E, approximately 1.442.

5 LOG10E
Base 10 logarithm of E, approximately 0.434.

6 PI
Ratio of the circumference of a circle to its diameter, approximately 3.14159.

7 SQRT1_2
Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.

8 SQRT2
Square root of 2, approximately 1.414.
In the following sections, we will have a few examples to demonstrate the usage of Math
properties.

Math Methods
Here is a list of the methods associated with Math object and their description

[Link]. Method & Description

1 abs()
Returns the absolute value of a number.

2 acos()
Returns the arccosine (in radians) of a number.

3 asin()
Returns the arcsine (in radians) of a number.

4 atan()
Returns the arctangent (in radians) of a number.

5 atan2()
Returns the arctangent of the quotient of its arguments.

6 ceil()
Returns the smallest integer greater than or equal to a number.

7 cos()
Returns the cosine of a number.

8 exp()
Returns E , where N is the argument, and E is Euler's constant, the base of the natural
N

logarithm.

9 floor()
Returns the largest integer less than or equal to a number.

10 log()
Returns the natural logarithm (base E) of a number.

11 max()
Returns the largest of zero or more numbers.

12 min()
Returns the smallest of zero or more numbers.

13 pow()
Returns base to the exponent power, that is, base exponent.

14 random()
Returns a pseudo-random number between 0 and 1.

15 round()
Returns the value of a number rounded to the nearest integer.

16 sin()
Returns the sine of a number.

17 sqrt()
Returns the square root of a number.

18 tan()
Returns the tangent of a number.

19 toSource()
Returns the string "Math".

In the following sections, we will have a few examples to demonstrate the usage of the
methods associated with Math.

JavaScript - Errors & Exceptions Handling


There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and
(c) Logical Errors.

Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional programming
languages and at interpret time in JavaScript.
For example, the following line causes a syntax error because it is missing a closing
parenthesis.
<script type = "text/javascript">
<!--
[Link](;
//-->
</script>
When a syntax error occurs in JavaScript, only the code contained within the same thread as
the syntax error is affected and the rest of the code in other threads gets executed assuming
nothing in them depends on the code containing the error.

Runtime Errors
Runtime errors, also called exceptions, occur during execution (after
compilation/interpretation).
For example, the following line causes a runtime error because here the syntax is correct, but
at runtime, it is trying to call a method that does not exist.
<script type = "text/javascript">
<!--
[Link]();
//-->
</script>
Exceptions also affect the thread in which they occur, allowing other JavaScript threads to
continue normal execution.

Logical Errors
Logic errors can be the most difficult type of errors to track down. These errors are not the
result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic
that drives your script and you do not get the result you expected.
You cannot catch those errors, because it depends on your business requirement what type of
logic you want to put in your program.

The try...catch...finally Statement


The latest versions of JavaScript added exception handling capabilities. JavaScript
implements the try...catch...finally construct as well as the throw operator to handle
exceptions.
You can catch programmer-generated and runtime exceptions, but you
cannot catch JavaScript syntax errors.
Here is the try...catch...finally block syntax −

<script type = "text/javascript">


<!--
try {
// Code to run
[break;]
}
catch ( e ) {
// Code to run if an exception occurs
[break;]
}

[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
//-->
</script>

The try block must be followed by either exactly one catch block or one finally block (or
one of both). When an exception occurs in the try block, the exception is placed in e and
the catch block is executed. The optional finally block executes unconditionally after
try/catch.
Examples
Here is an example where we are trying to call a non-existing function which in turn is
raising an exception. Let us see how it behaves without try...catch−
Live Demo

<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
alert("Value of variable a is : " + a );
}
//-->
</script>
</head>

<body>
<p>Click the following to see the result:</p>

<form>
<input type = "button" value = "Click Me" />
</form>
</body>
</html>

Output
Now let us try to catch this exception using try...catch and display a user-friendly message.
You can also suppress this message, if you want to hide this error from a user.
Live Demo

<html>
<head>

<script type = "text/javascript">


<!--
function myFunc() {
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + [Link] );
}
}
//-->
</script>

</head>
<body>
<p>Click the following to see the result:</p>

<form>
<input type = "button" value = "Click Me" />
</form>

</body>
</html>

Output
You can use finally block which will always execute unconditionally after the try/catch. Here
is an example.
Live Demo

<html>
<head>

<script type = "text/javascript">


<!--
function myFunc() {
var a = 100;

try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + [Link] );
}
finally {
alert("Finally block will always execute!" );
}
}
//-->
</script>

</head>
<body>
<p>Click the following to see the result:</p>

<form>
<input type = "button" value = "Click Me" />
</form>

</body>
</html>

Output

The throw Statement


You can use throw statement to raise your built-in exceptions or your customized exceptions.
Later these exceptions can be captured and you can take an appropriate action.
Example
The following example demonstrates how to use a throw statement.
Live Demo

<html>
<head>

<script type = "text/javascript">


<!--
function myFunc() {
var a = 100;
var b = 0;

try {
if ( b == 0 ) {
throw( "Divide by zero error." );
} else {
var c = a / b;
}
}
catch ( e ) {
alert("Error: " + e );
}
}
//-->
</script>

</head>
<body>
<p>Click the following to see the result:</p>

<form>
<input type = "button" value = "Click Me" />
</form>

</body>
</html>

Output
You can raise an exception in one function using a string, integer, Boolean, or an object and
then you can capture that exception either in the same function as we did above, or in another
function using a try...catch block.

The onerror() Method


The onerror event handler was the first feature to facilitate error handling in JavaScript.
The error event is fired on the window object whenever an exception occurs on the page.
Live Demo

<html>
<head>

<script type = "text/javascript">


<!--
[Link] = function () {
alert("An error occurred.");
}
//-->
</script>

</head>
<body>
<p>Click the following to see the result:</p>

<form>
<input type = "button" value = "Click Me" />
</form>

</body>
</html>
Output
The onerror event handler provides three pieces of information to identify the exact nature of
the error −
 Error message − The same message that the browser would display for the
given error
 URL − The file in which the error occurred
 Line number− The line number in the given URL that caused the error
Here is the example to show how to extract this information.
Example
Live Demo

<html>
<head>

<script type = "text/javascript">


<!--
[Link] = function (msg, url, line) {
alert("Message : " + msg );
alert("url : " + url );
alert("Line number : " + line );
}
//-->
</script>

</head>
<body>
<p>Click the following to see the result:</p>

<form>
<input type = "button" value = "Click Me" />
</form>

</body>
</html>

Output
You can display extracted information in whatever way you think it is better.
You can use an onerror method, as shown below, to display an error message in case there is
any problem in loading an image.

<img src="[Link]" error occurred loading the image.')" />

You can use onerror with many HTML tags to display appropriate messages in case of
errors.

JavaScript - Form Validation


Form validation normally used to occur at the server, after the client had entered all the
necessary data and then pressed the Submit button. If the data entered by a client was
incorrect or was simply missing, the server would have to send all the data back to the client
and request that the form be resubmitted with correct information. This was really a lengthy
process which used to put a lot of burden on the server.
JavaScript provides a way to validate form's data on the client's computer before sending it to
the web server. Form validation generally performs two functions.
 Basic Validation − First of all, the form must be checked to make sure all the
mandatory fields are filled in. It would require just a loop through each field in
the form and check for data.
 Data Format Validation − Secondly, the data that is entered must be checked
for correct form and value. Your code must include appropriate logic to test
correctness of data.
Example
We will take an example to understand the process of validation. Here is a simple form in
html format.
Live Demo

<html>
<head>
<title>Form Validation</title>
<script type = "text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>

<body>
<form action = "/cgi-bin/[Link]" name = "myForm" >"return(validate());">
<table cellspacing = "2" cellpadding = "2" border = "1">

<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr>

<tr>
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td>
</tr>

<tr>
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>
<tr>
<td align = "right">Country</td>
<td>
<select name = "Country">
<option value = "-1" selected>[choose yours]</option>
<option value = "1">USA</option>
<option value = "2">UK</option>
<option value = "3">INDIA</option>
</select>
</td>
</tr>

<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>

</table>
</form>
</body>
</html>

Output

Basic Form Validation


First let us see how to do a basic form validation. In the above form, we are
calling validate() to validate data when onsubmit event is occurring. The following code
shows the implementation of this validate() function.

<script type = "text/javascript">


<!--
// Form validation code will come here.
function validate() {

if( [Link] == "" ) {


alert( "Please provide your name!" );
[Link]() ;
return false;
}
if( [Link] == "" ) {
alert( "Please provide your Email!" );
[Link]() ;
return false;
}
if( [Link] == "" || isNaN( [Link] ) ||
[Link] != 5 ) {
alert( "Please provide a zip in the format #####." );
[Link]() ;
return false;
}
if( [Link] == "-1" ) {
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>

Data Format Validation


Now we will see how we can validate our entered form data before submitting it to the web
server.
The following example shows how to validate an entered email address. An email address
must contain at least a ‘@’ sign and a dot (.). Also, the ‘@’ must not be the first character of
the email address, and the last dot must at least be one character after the ‘@’ sign.
Example
Try the following code for email validation.

<script type = "text/javascript">


<!--
function validateEmail() {
var emailID = [Link];
atpos = [Link]("@");
dotpos = [Link](".");

if (atpos < 1 || ( dotpos - atpos < 2 )) {


alert("Please enter correct email ID")
[Link]() ;
return false;
}
return( true );
}
//-->
</script>

JavaScript - Debugging
Every now and then, developers commit mistakes while coding. A mistake in a program or a
script is referred to as a bug.
The process of finding and fixing bugs is called debugging and is a normal part of the
development process. This section covers tools and techniques that can help you with
debugging tasks..

Error Messages in IE
The most basic way to track down errors is by turning on error information in your browser.
By default, Internet Explorer shows an error icon in the status bar when an error occurs on the
page.

Double-clicking this icon takes you to a dialog box showing information about the specific
error that occurred.
Since this icon is easy to overlook, Internet Explorer gives you the option to automatically
show the Error dialog box whenever an error occurs.
To enable this option, select Tools → Internet Options → Advanced tab. and then finally
check the "Display a Notification About Every Script Error" box option as shown below

Error Messages in Firefox or Mozilla


Other browsers like Firefox, Netscape, and Mozilla send error messages to a special window
called the JavaScript Console or Error Consol. To view the console, select Tools → Error
Consol or Web Development.
Unfortunately, since these browsers give no visual indication when an error occurs, you must
keep the Console open and watch for errors as your script executes.

You might also like