Java Script
Java Script
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.
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;
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;
Output
Does not qualify for driving
Set the variable to different value and then try...
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;
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;
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.
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>
[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...
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;
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 −
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 />");
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.
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 /> ");
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.
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 /> ");
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...
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>
</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 −
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
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.
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
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>
<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
Triggers when media can start play, but might has to stop
Oncanplay script
for buffering
Onloadstart script Triggers when the browser starts to load the media data
Onmouseout script Triggers when the mouse pointer moves out of an element
Onmouseover script Triggers when the mouse pointer moves over an element
Onprogress script Triggers when the browser is fetching the media data
Onratechange script Triggers when the media data's playing rate has changed
<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
<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
<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.
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");
<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
<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;
}
Output
Book title is : Perl
Book author is : Mohtashim
Book price is : 100
<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);
Output
Book title is : Perl
Book author is : Mohtashim
Book price is : 100
Number Properties
Here is a list of each property and their 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.
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.
Boolean Properties
Here is a list of the properties of Boolean object −
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.
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.
String Properties
Here is a list of the properties of String object and their 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.
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.
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.
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.
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.
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.
Date Properties
Here is a list of the properties of the Date object along with their 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.
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.
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.
Math Properties
Here is a list of all the properties of Math and their 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
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.
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.
[ 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>
</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>
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
<html>
<head>
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.
<html>
<head>
</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>
</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.
You can use onerror with many HTML tags to display appropriate messages in case of
errors.
<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
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
−