Javascript Material 1
Javascript Material 1
Javascript Material 1
JavaScript is lightweight and most commonly used as a part of web pages, whose
implementations allow client-side script to interact with the user and make dynamic
pages. It is an interpreted programming language with object-oriented capabilities. It is
open and cross-platform.
JavaScript was first known as Live Script, but Netscape changed its name
Client-side JavaScript
Client-side JavaScript is the most common form of the language. The script should be
included in or referenced by an HTML document for the code to be interpreted by the
browser.
The JavaScript client-side mechanism provides many advantages over traditional CGI
server-side scripts. For example, you might use JavaScript to check if the user has
entered a valid e-mail address in a form field.
Advantages of JavaScript
• Less server interaction − You can validate user input before sending the
page off to the server. This saves server traffic, which means less load on
your server.
• Immediate feedback to the visitors − They don't have to wait for a page
reload to see if they have forgotten to enter something.
• Increased interactivity − You can create interfaces that react when the
user hovers over them with a mouse or activates them via the keyboard.
• Richer interfaces − You can use JavaScript to include such items as drag-
and-drop components and sliders to give a Rich Interface to your site
visitors.
JavaScript - Syntax
JavaScript can be implemented using JavaScript statements that are placed within
the <script>... </script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within your
web page, but it is normally recommended that you should keep it within
the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between
these tags as a script. A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>
• Language − This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of HTML (and
XHTML, its successor) have phased out the use of this attribute.
JavaScript code
</script>
<html>
<body>
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
Hello World!
<!--
var1 = 10
var2 = 20
//-->
</script>
But when formatted in a single line as follows, you must use semicolons −
<!--
//-->
</script>
Case Sensitivity
JavaScript is a case-sensitive language. This means that the language keywords,
variables, function names, and any other identifiers must always be typed with a
consistent capitalization of letters.
Comments in JavaScript
JavaScript supports both C-style and C++-style comments, Thus −
• Any text between a // and the end of a line is treated as a comment and is
ignored by JavaScript.
• Any text between the characters /* and */ is treated as a comment. This may
span multiple lines.
<!--
/*
*/
//-->
</script>
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
//-->
</script>
</head>
<body>
</body>
</html>
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
</body>
</html>
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
</body>
</html>
You are not restricted to be maintaining identical code in multiple HTML files.
The script tag provides a mechanism to allow you to store JavaScript in an external
file and then include it into your HTML files.
Here is an exampl e to show how you can include an external JavaScript file in your
HTML code using script tag and its src attribute.
<html>
<head>
</head>
<body>
.......
</body>
</html>
To use JavaScript from an external file source, you need to write all your JavaScript
source code in a simple text file with the extension ".js" and then include that file as
shown above.
For example, you can keep the following content in filename.js file and then you can
use sayHello function in your HTML file after including the filename.js file.
function sayHello() {
alert("Hello World")
JavaScript - Variables
JavaScript Data types
One of the most fundamental characteristics of a programming language is the set of
data types it supports. These are the type of values that can be represented and
manipulated in a programming language.
JavaScript Variables
Like many other programming languages, JavaScript has variables. Variables can be
thought of as named containers. You can place data into these containers and then
refer to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are
declared with the var keyword as follows.
<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>
You can also declare multiple variables with the same var keyword as follows −
<script type="text/javascript">
<!--
var money, name;
//-->
</script>
For instance, you might create a variable named money and assign the value 2000.50
to it later. For another variable, you can assign a value at the time of initialization as
follows.
<script type="text/javascript">
<!--
var money;
money = 2000.50;
//-->
</script>
• Global Variables − A global variable has global scope which means it can be
defined anywhere in your JavaScript code.
• Local Variables − A local variable will be visible only within a function where it
is defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable
with the same name. If you declare a local variable or function parameter with the
same name as a global variable, you effectively hide the global variable. Take a look
into the following example.
<html>
<!--
function checkscope( ) {
document.write(myVar);
//-->
</script>
</body>
</html>
local
• You should not use any of the JavaScript reserved keywords as a variable name.
These keywords are mentioned in the next section. For
example, break or boolean variable names are not valid.
• JavaScript variable names should not start with a numeral (0-9). They must
begin with a letter or an underscore character. For example, 123test is an
invalid variable name but _123test is a valid one.
double in super
JavaScript - Operators
What is an operator?
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are
called operands and ‘+’ is called the operator. JavaScript supports the following types
of operators.
• Arithmetic Operators
• Comparision Operators
• Assignment Operators
Arithmetic Operators
JavaScript supports the following arithmetic operators −
1 + (Addition)
2 - (Subtraction)
3 * (Multiplication)
4 / (Division)
5 % (Modulus)
Outputs the remainder of an integer division
6 ++ (Increment)
7 -- (Decrement)
Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a"
+ 10 will give "a10".
<html>
<body>
<script type="text/javascript">
<!--
var a = 33;
var b = 10;
var c = "Test";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);
a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);
b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
//-->
</script>
Set the variables to different values and then try...
</body>
</html>
Output
a + b = 43
a - b = 23
a / b = 3.3
a % b = 3
a + b + c = 43Test
++a = 35
--b = 8
Set the variables to different values and then try...
Comparison Operators
JavaScript supports the following comparison operators −
1 = = (Equal)
Checks if the value of two operands are equal or not, if yes, then the
condition becomes true.
2 != (Not Equal)
Checks if the value of two operands are equal or not, if the values are
not equal, then the condition becomes true.
Ex: (A != B) is true.
Checks if the value of the left operand is greater than the value of the
right operand, if yes, then the condition becomes true.
Ex: (A > B) is not true.
Checks if the value of the left operand is less than the value of the right
operand, if yes, then the condition becomes true.
Checks if the value of the left operand is greater than or equal to the
value of the right operand, if yes, then the condition becomes true.
Checks if the value of the left operand is less than or equal to the value
of the right operand, if yes, then the condition becomes true.
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
result = (a == b);
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak);
result = (a != b);
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak);
//-->
</script>
Set the variables to different values and different operators and then try...
</body>
</html>
Output
(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false
a <= b) => true
Set the variables to different values and different operators and then try...
Logical Operators
JavaScript supports the following logical operators −
If both the operands are non-zero, then the condition becomes true.
2 || (Logical OR)
If any of the two operands are non-zero, then the condition becomes
true.
Ex: (A || B) is true.
3 ! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the
Logical NOT operator will make it false.
<html>
<body>
<script type="text/javascript">
<!--
var a = true;
var b = false;
document.write(result);
document.write(linebreak);
result = (a || b);
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>
Output
(a && b) => false
(a || b) => true
!(a && b) => true
Set the variables to different values and different operators and then try...
Assignment Operators
JavaScript supports the following assignment operators −
1 = (Simple Assignment )
Assigns values from the right side operand to the left side operand
It adds the right operand to the left operand and assigns the result to
the left operand.
Ex: C += A is equivalent to C = C + A
It subtracts the right operand from the left operand and assigns the
result to the left operand.
Ex: C -= A is equivalent to C = C - A
It multiplies the right operand with the left operand and assigns the
result to the left operand.
Ex: C *= A is equivalent to C = C * A
It divides the left operand with the right operand and assigns the result
to the left operand.
Ex: C /= A is equivalent to C = C / A
6 %= (Modules and Assignment)
It takes modulus using two operands and assigns the result to the left
operand.
Ex: C %= A is equivalent to C = C % A
Note − Same logic applies to Bitwise operators so they will become like
<<=, >>=, >>=, &=, |= and ^=.
<html>
<body>
<script type="text/javascript">
<!--
var a = 33;
var b = 10;
result = (a = b);
document.write(result);
document.write(linebreak);
result = (a += b);
document.write(result);
document.write(linebreak);
result = (a -= b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a *= b) => ");
result = (a *= b);
document.write(result);
document.write(linebreak);
result = (a /= b);
document.write(result);
document.write(linebreak);
result = (a %= b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>
Output
Value of a => (a = b) => 10
Value of a => (a += b) => 20
Value of a => (a -= b) => 10
Value of a => (a *= b) => 100
Value of a => (a /= b) => 10
Value of a => (a %= b) => 0
Set the variables to different values and different operators and then try...
Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then
executes one of the two given statements depending upon the result of the evaluation.
Try the following code to understand how the Conditional Operator works in
JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>
Output
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
Set the variables to different values and different operators and then try...
Type of Operator
The typeof operator is a unary operator that is placed before its single operand, which
can be of any type. Its value is a string indicating the data type of the operand.
Number "number"
String "string"
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = "String";
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>
Output
Result => B is String
Result => A is Numeric
Set the variables to different values and different operators and then try...
JavaScript supports conditional statements which are used to perform different actions
based on different conditions. Here we will explain the if..else statement.
• if...else 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){
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.
<html>
<body>
<script type="text/javascript">
<!--
//-->
</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){
else{
Try the following code to learn how to implement an if-else statement in JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
else{
document.write("<b>Does not qualify for driving</b>");
//-->
</script>
</body>
</html>
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){
else{
}
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.
<html>
<body>
<script type="text/javascript">
<!--
document.write("<b>History Book</b>");
document.write("<b>Maths Book</b>");
document.write("<b>Economics Book</b>");
else{
document.write("<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...
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 ifstatements.
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)
break;
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.
<html>
<body>
<script type="text/javascript">
<!--
var grade='A';
switch (grade)
break;
break;
break;
break;
break;
default: document.write("Unknown grade<br />")
//-->
</script>
</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.
<html>
<body>
<script type="text/javascript">
<!--
var grade='A';
switch (grade)
</script>
</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...
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){
<html>
<body>
<script type="text/javascript">
<!--
var count = 0;
count++;
document.write("Loop stopped!");
//-->
</script>
</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);
<html>
<body>
<script type="text/javascript">
<!--
var count = 0;
do{
document.write("Current Count : " + count + "<br />");
count++;
//-->
</script>
</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...
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 −
Try the following example to learn how a for loop works in JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var count;
document.write("<br />");
document.write("Loop stopped!");
//-->
</script>
</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 break statement would look as follows −
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 document.write
(..) statement just below to the closing curly brace −
<html>
<body>
<script type="text/javascript">
<!--
var x = 1;
if (x == 5){
x = x + 1;
//-->
</script>
</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 switchstatement.
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 −
<html>
<body>
<script type="text/javascript">
<!--
var x = 1;
x = x + 1;
if (x == 5){
//-->
</script>
</body>
</html>
Output
Entering the loop
2
3
4
6
7
8
9
10
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
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.
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>
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.
<html>
<head>
<script type="text/javascript">
function sayHello()
</script>
</head>
<body>
<form>
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>
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.
Try the following example. We have modified our sayHello function here. Now it takes
two parameters.
<html>
<head>
<script type="text/javascript">
</script>
</head>
<body>
<form>
</form>
</body>
</html>
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.
Try the following example. It defines a function that takes two parameters and
concatenates them before returning the resultant in the calling program.
<html>
<head>
<script type="text/javascript">
var full;
return full;
function secondFunction()
var result;
document.write (result );
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
</form>
</body>
</html>
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.
onClick Event
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.
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
//-->
</script>
</head>
<body>
<form>
</form>
</body>
</html>
onsubmit Event
onsubmit is an event that occurs when you try to submit a form. You can put your form
validation against this event type.
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.
<html>
<head>
<script type="text/javascript">
<!--
function validation() {
all validation goes here
.........
//-->
</script>
</head>
<body>
.......
</form>
</body>
</html>
<html>
<head>
<script type="text/javascript">
<!--
function over() {
function out() {
document.write ("Mouse Out");
//-->
</script>
</head>
<body>
</div>
</body>
</html>
There could be various reasons why you would like to redirect a user from the original
page. We are listing down a few of the reasons −
• You did not like the name of your domain and you are moving to a new one. In
such a scenario, you may want to direct all your visitors to the new site. Here
you can maintain your old domain but put a single page with a page redirection
such that all your old domain visitors can come to your new domain.
• You have built-up various pages based on browser versions or their names or
may be based on different countries, then instead of using your server-side
page redirection, you can use client-side page redirection to land your users on
the appropriate page.
• The Search Engines may have already indexed your pages. But while moving to
another domain, you would not like to lose your visitors coming through search
engines. So you can use client-side page redirection. But keep in mind this
should not be done to fool the search engine, it could lead your site to get
banned.
It is quite simple to do a page redirect using JavaScript at client side. To redirect your
site visitors to a new page, you just need to add a line in your head section as follows.
<html>
<head>
<script type="text/javascript">
<!--
function Redirect() {
window.location="http://www.tutorialspoint.com";
//-->
</script>
</head>
<body>
<form>
</form>
</body>
</html>
Example 2
<html>
<head>
<script type="text/javascript">
<!--
function Redirect() {
window.location="http://www.tutorialspoint.com";
setTimeout('Redirect()', 10000);
//-->
</script>
</head>
<body>
</body>
</html>
Output
You will be redirected to tutorialspoint.com main page in 10 seconds!
Example
The following example shows how to redirect your site visitors onto a
different page based on their browsers.
<html>
<head>
<script type="text/javascript">
<!--
var browsername=navigator.appName;
if( browsername == "Netscape" )
window.location="http://www.location.com/ns.htm";
window.location="http://www.location.com/ie.htm";
else
window.location="http://www.location.com/other.htm";
//-->
</script>
</head>
<body>
</body>
</html>
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only
one button "OK" to select and proceed.
<html>
<head>
<script type="text/javascript">
<!--
function Warn() {
//-->
</script>
</head>
<body>
<form>
</form>
</body>
</html>
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.
<html>
<head>
<script type="text/javascript">
<!--
function getConfirmation(){
return true;
else{
return false;
//-->
</script>
</head>
<body>
<form>
</form>
</body>
</html>
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.
<html>
<head>
<script type="text/javascript">
<!--
function getValue(){
//-->
</script>
</head>
<body>
<form>
</form>
</body>
</html>
<html>
<head>
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<form>
</form>
</body>
<html>
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.
document.write("This is test");
User-Defined Objects
All user-defined objects and built-in objects are descendants of an object
called Object.
In the following example, the constructor methods are Object(), Array(), and Date().
These constructors are built-in JavaScript functions.
Syntax
The syntax for creating a number object is as follows −
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).
Syntax
Use the following syntax to create a String object −
String Methods
Here is a list of the methods available in String object along with their description.
Method Description
indexOf() Returns the index within the calling String object of the
first occurrence of the specified value, or -1 if not
found.
lastIndexOf() Returns the index within the calling String object of the
last occurrence of the specified value, or -1 if not
found.
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 −
You will use ordinal numbers to access and to set values inside an array as follows.
Array Methods
Here is a list of the methods of the Array object along with their description.
Method Description
concat() Returns a new array comprised of this array joined with other
array(s) and/or value(s).
filter() Creates a new array with all of the elements of this array for
which the provided filtering function returns true.
indexOf() Returns the first (least) index of an element within the array
equal to the specified value, or -1 if none is found.
pop() Removes the last element from an array and returns that
element.
push() Adds one or more elements to the end of an array and returns
the new length of the array.
shift() Removes the first element from an array and returns that
element.
some() Returns true if at least one element in this array satisfies the
provided testing function.
toSource() Represents the source code of an object
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.
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 ])
• 7 agruments − To use the last form of the constructor shown above. Here is a
description of each argument:
• 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.
• hour − Integer value representing the hour of the day (24-hour scale).
Date Methods
Here is a list of the methods used with Date and their description.
Method Description
getDate() Returns the day of the month for the specified date
according to local time.
getDay() Returns the day of the week for the specified date
according to local time.
setFullYear() Sets the full year for a specified date according to local
time.
Syntax
The syntax to call the properties and methods of Math are as follows
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
Method Description
pow() Returns base to the exponent power, that is, base exponent.
Syntax
A regular expression could be defined with the RegExp () constructor, as follows −
or simply
• attributes − An optional string containing any of the "g", "i", and "m" attributes
that specify global, case-insensitive, and multiline matches, respectively.
Brackets
Brackets ([]) have a special meaning when used in the context of regular expressions.
They are used to find a range of characters.
Expression Description
The ranges shown above are general; you could also use the range [0-3] to match any
decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase
character ranging from b through v.
Literal characters
Character Description
Alphanumeric Itself
\t Tab (\u0009)
\n Newline (\u000A)
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">
<!--
window.print(;
//-->
</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">
<!--
window.printme();
//-->
</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.
<script type="text/javascript">
<!--
try {
// Code to run
[break;]
catch ( e ) {
[break;]
[ finally {
// an exception occurring
}]
//-->
</script>
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−
<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
var a = 100;
//-->
</script>
</head>
<body>
<form>
</form>
</body>
</html>
<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
var a = 100;
try {
catch ( e ) {
//-->
</script>
</head>
<body>
<form>
</form>
</body>
</html>
Output
You can use finally block which will always execute unconditionally after the try/catch.
Here is an example.
<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;
try {
catch ( e ) {
finally {
//-->
</script>
</head>
<body>
<form>
</form>
</body>
</html>
<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
var a = 100;
var b = 0;
try{
if ( b == 0 ){
else
var c = a / b;
catch ( e ) {
alert("Error: " + e );
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
</form>
</body>
</html>
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.
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.
We will take an example to understand the process of validation. Here is a simple form
in html format.
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<tr>
<td align="right">Name</td>
</tr>
<tr>
<td align="right">EMail</td>
</tr>
<tr>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
</tr>
</table>
</form>
</body>
</html>
<script type="text/javascript">
<!--
function validate()
return false;
document.myForm.EMail.focus() ;
return false;
isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
document.myForm.Zip.focus() ;
return false;
return false;
return( true );
//-->
</script>
<script type="text/javascript">
<!--
function validateEmail()
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
document.myForm.EMail.focus() ;
return false;
return( true );
//-->
</script>
<script>
function validate(){
var fname=document.f1.fname.value;
var lname=document.f1.lname.value;
var status=false;
if(fname=="")
document.getElementById('fnamenote').style.fontSize=30px;
status=false;
else
status=true;
if(lname=="")
status=false;
else
status=true;
return status;
}
</script>
</form>