Javascript Tutorial: Where Javascript Is Used

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 74

JavaScript Tutorial

JavaScript Tutorial for beginners and professionals is a solution of client side dynamic


pages.

JavaScript is an object-based scripting language that is lightweight and cross-platform.

JavaScript is not compiled but translated. The JavaScript Translator (embedded in


browser) is responsible to translate the JavaScript code.

Where JavaScript is used


JavaScript is used to create interactive websites. It is mainly used for:

o Client-side validation

o Dynamic drop-down menus

o Displaying data and time

o Displaying popup windows and dialog boxes (like alert dialog box, confirm dialog
box and prompt dialog box)
o Displaying clocks etc.
JavaScript Example
1. <h2>Welcome to JavaScript</h2>  
2. <script>  
3. document.write("Hello JavaScript by JavaScript");  
4. </script>  
Test it Now

Prerequisite
Before learning JavaScript, you must have the basic knowledge of HTML.

Audience
We have developed this JavaScript tutorial for beginners and professionals. There are
given a lot of examples with JavaScript editor. You will get point to point explanation of
each JavaScript topics. Our tutorial will help beginners and professionals to learn
JavaScript easily.

Problem
If there is any problem related to JavaScript, you can post your question in forum. We
will definitely sort out your problems

JavaScript Example
1. JavaScript Example
2. Within body tag
3. Within head tag

Javascript example is easy to code. JavaScript provides 3 places to put the JavaScript
code: within body tag, within head tag and external JavaScript file.

Let’s create the first JavaScript example.

1. <script type="text/javascript">  
2. document.write("JavaScript is a simple language for javatpoint learners");  
3. </script>  
Test it Now
The script tag specifies that we are using JavaScript.

The text/javascript is the content type that provides information to the browser about
the data.

The document.write() function is used to display dynamic content through JavaScript.


We will learn about document object in detail later.

3 Places to put JavaScript code


1. Between the body tag of html

2. Between the head tag of html

3. In .js file (external javaScript)

1) JavaScript Example : code between the body tag


In the above example, we have displayed the dynamic content using JavaScript. Let’s
see the simple example of JavaScript that displays alert dialog box.

1. <script type="text/javascript">  
2.  alert("Hello Javatpoint");  
3. </script>  
Test it Now

2) JavaScript Example : code between the head tag


Let’s see the same example of displaying alert dialog box of JavaScript that is contained
inside the head tag.

In this example, we are creating a function msg(). To create function in JavaScript, you
need to write function with function_name as given below.

To call function, you need to work on event. Here we are using onclick event to call
msg() function.

1. <html>  
2. <head>  
3. <script type="text/javascript">  
4. function msg(){  
5.  alert("Hello Javatpoint");  
6. }  
7. </script>  
8. </head>  
9. <body>  
10. <p>Welcome to JavaScript</p>  
11. <form>  
12. <input type="button" value="click" onclick="msg()"/>  
13. </form>  
14. </body>  
15. </html>  

External JavaScript file


We can create external JavaScript file and embed it in many html page.

It provides code re usability because single JavaScript file can be used in several html


pages.

An external JavaScript file must be saved by .js extension. It is recommended to embed


all JavaScript files into a single file. It increases the speed of the webpage.

Let’s create an external JavaScript file that prints Hello Javatpoint in a alert dialog box.

message.js

1. function msg(){  
2.  alert("Hello Javatpoint");  
3. }  

Let’s include the JavaScript file into html page. It calls the JavaScript function on button
click.

index.html

1. <html>  
2. <head>  
3. <script type="text/javascript" src="message.js"></script>  
4. </head>  
5. <body>  
6. <p>Welcome to JavaScript</p>  
7. <form>  
8. <input type="button" value="click" onclick="msg()"/>  
9. </form>  
10. </body>  
11. </html>  

JavaScript Comment
1. JavaScript comments
2. Advantage of javaScript comments
3. Single-line and Multi-line comments

The JavaScript comments are meaningful way to deliver message. It is used to add


information about the code, warnings or suggestions so that end user can easily
interpret the code.

The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the
browser.

Advantages of JavaScript comments


There are mainly two advantages of JavaScript comments.

1. To make code easy to understand It can be used to elaborate the code so that
end user can easily understand the code.

2. To avoid the unnecessary code It can also be used to avoid the code being
executed. Sometimes, we add the code to perform some action. But after
sometime, there may be need to disable the code. In such case, it is better to use
comments.

Types of JavaScript Comments


There are two types of comments in JavaScript.

1. Single-line Comment

2. Multi-line Comment
JavaScript Single line Comment
It is represented by double forward slashes (//). It can be used before and after the
statement.

Let’s see the example of single-line comment i.e. added before the statement.

1. <script>  
2. // It is single line comment  
3. document.write("hello javascript");  
4. </script>  
Test it Now

Let’s see the example of single-line comment i.e. added after the statement.

1. <script>  
2. var a=10;  
3. var b=20;  
4. var c=a+b;//It adds values of a and b variable  
5. document.write(c);//prints sum of 10 and 20  
6. </script>  
Test it Now

JavaScript Multi line Comment


It can be used to add single as well as multi line comments. So, it is more convenient.

It is represented by forward slash with asterisk then asterisk with forward slash. For
example:

1. /* your code here  */  

It can be used before, after and middle of the statement.

1. <script>  
2. /* It is multi line comment.  
3. It will not be displayed */  
4. document.write("example of javascript multiline comment");  
5. </script>  
JavaScript Variable
1. JavaScript variable
2. JavaScript Local variable
3. JavaScript Global variable

A JavaScript variable is simply a name of storage location. There are two types of
variables in JavaScript : local variable and global variable.

There are some rules while declaring a JavaScript variable (also known as identifiers).

1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ )


sign.

2. After first letter we can use digits (0 to 9), for example value1.

3. JavaScript variables are case sensitive, for example x and X are different
variables.

Correct JavaScript variables

1. var x = 10;  
2. var _value="sonoo";  

Incorrect JavaScript variables

1. var  123=30;  
2. var *aa=320;  

Example of JavaScript variable


Let’s see a simple example of JavaScript variable.

1. <script>  
2. var x = 10;  
3. var y = 20;  
4. var z=x+y;  
5. document.write(z);  
6. </script>  
Test it Now
Output of the above example
30

JavaScript local variable


A JavaScript local variable is declared inside block or function. It is accessible within the
function or block only. For example:

1. <script>  
2. function abc(){  
3. var x=10;//local variable  
4. }  
5. </script>  

Or,

1. <script>  
2. If(10<13){  
3. var y=20;//JavaScript local variable  
4. }  
5. </script>  

JavaScript global variable


A JavaScript global variable is accessible from any function. A variable i.e. declared
outside the function or declared with window object is known as global variable. For
example:

1. <script>  
2. var data=200;//gloabal variable  
3. function a(){  
4. document.writeln(data);  
5. }  
6. function b(){  
7. document.writeln(data);  
8. }  
9. a();//calling JavaScript function  
10. b();  
11. </script>  
JavaScript Global Variable
A JavaScript global variable is declared outside the function or declared with window
object. It can be accessed from any function.

Let’s see the simple example of global variable in JavaScript.

1. <script>  
2. var value=50;//global variable  
3. function a(){  
4. alert(value);  
5. }  
6. function b(){  
7. alert(value);  
8. }  
9. </script>  
Test it Now

Declaring JavaScript global variable within function


To declare JavaScript global variables inside function, you need to use window object.
For example:

1. window.value=90;  

Now it can be declared inside any function and can be accessed from any function. For
example:

1. function m(){  
2. window.value=100;//declaring global variable by window object  
3. }  
4. function n(){  
5. alert(window.value);//accessing global variable from other function  
6. }  
Test it Now

Internals of global variable in JavaScript


When you declare a variable outside the function, it is added in the window object
internally. You can access it through window object also. For example:

1. var value=50;  
2. function a(){  
3. alert(window.value);//accessing global variable   
4. }  

Javascript Data Types


JavaScript provides different data types to hold different types of values. There are two
types of data types in JavaScript.

1. Primitive data type

2. Non-primitive (reference) data type

JavaScript is a dynamic type language, means you don't need to specify type of the
variable because it is dynamically used by JavaScript engine. You need to use var here
to specify the data type. It can hold any type of values such as numbers, strings etc. For
example:

1. var a=40;//holding number  
2. var b="Rahul";//holding string  

JavaScript primitive data types


There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description

String represents sequence of characters e.g. "hello"

Number represents numeric values e.g. 100

Boolean represents boolean value either false or true

Undefine represents undefined value


d

Null represents null i.e. no value at all


JavaScript non-primitive data types
The non-primitive data types are as follows:

Data Description
Type

Object represents instance through which we can access members

Array represents group of similar values

RegExp represents regular expression

We will have great discussion on each data type later.

JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For
example:

1. var sum=10+20;  

Here, + is the arithmetic operator and = is the assignment operator.

There are following types of operators in JavaScript.

1. Arithmetic Operators

2. Comparison (Relational) Operators

3. Bitwise Operators

4. Logical Operators

5. Assignment Operators

6. Special Operators

JavaScript Arithmetic Operators


Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as JavaScript arithmetic operators.
Operato Description Example
r

+ Addition 10+20 = 30

- Subtraction 20-10 = 10

* Multiplication 10*20 = 200

/ Division 20/10 = 2

% Modulus (Remainder) 20%10 = 0

++ Increment var a=10; a++; Now a = 11

-- Decrement var a=10; a--; Now a = 9

JavaScript Comparison Operators


The JavaScript comparison operator compares the two operands. The comparison
operators are as follows:

Operato Description Example


r

== Is equal to 10==20 = false

=== Identical (equal and of same type) 10==20 = false

!= Not equal to 10!=20 = true

!== Not Identical 20!==20 = false

> Greater than 20>10 = true

>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false

<= Less than or equal to 20<=10 = false


JavaScript Bitwise Operators
The bitwise operators perform bitwise operations on operands. The bitwise operators are
as follows:

Operato Description Example


r

& Bitwise AND (10==20 & 20==33) = false

| Bitwise OR (10==20 | 20==33) = false

^ Bitwise XOR (10==20 ^ 20==33) = false

~ Bitwise NOT (~10) = -10

<< Bitwise Left Shift (10<<2) = 40

>> Bitwise Right Shift (10>>2) = 2

>>> Bitwise Right Shift with Zero (10>>>2) = 2

JavaScript Logical Operators


The following operators are known as JavaScript logical operators.

Operato Description Example


r

&& Logical (10==20 && 20==33) = false


AND

|| Logical OR (10==20 || 20==33) = false

! Logical Not !(10==20) = true

JavaScript Assignment Operators


The following operators are known as JavaScript assignment operators.

Operato Description Example


r

= Assign 10+10 = 20

+= Add and assign var a=10; a+=20; Now a = 30

-= Subtract and var a=20; a-=10; Now a = 10


assign

*= Multiply and assign var a=10; a*=20; Now a = 200

/= Divide and assign var a=10; a/=2; Now a = 5

%= Modulus and assign var a=10; a%=2; Now a = 0

JavaScript Special Operators


The following operators are known as JavaScript special operators.

Operator Description

(?:) Conditional Operator returns value based on the condition. It is like if-
else.

, Comma Operator allows multiple expressions to be evaluated as single


statement.

delete Delete Operator deletes a property from the object.

in In Operator checks if object has the given property

instanceof checks if the object is an instance of given type

new creates an instance (object)

typeof checks the type of object.

void it discards the expression's return value.

yield checks what is returned in a generator by the generator's iterator.


JavaScript If-else
The JavaScript if-else statement is used to execute the code whether condition is
true or false. There are three forms of if statement in JavaScript.

1. If Statement

2. If else statement

3. if else if statement

JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if
statement is given below.

1. if(expression){  
2. //content to be evaluated  
3. }  
Flowchart of JavaScript If statement

Let’s see the simple example of if statement in javascript.

1. <script>  
2. var a=20;  
3. if(a>10){  
4. document.write("value of a is greater than 10");  
5. }  
6. </script>  
Test it Now

Output of the above example


value of a is greater than 10
JavaScript If...else Statement
It evaluates the content whether condition is true of false. The syntax of JavaScript if-
else statement is given below.

1. if(expression){  
2. //content to be evaluated if condition is true  
3. }  
4. else{  
5. //content to be evaluated if condition is false  
6. }  

Flowchart of JavaScript If...else statement

Let’s see the example of if-else statement in JavaScript to find out the even or odd
number.

1. <script>  
2. var a=20;  
3. if(a%2==0){  
4. document.write("a is even number");  
5. }  
6. else{  
7. document.write("a is odd number");  
8. }  
9. </script>  
Test it Now

Output of the above example


a is even number

JavaScript If...else if statement


It evaluates the content only if expression is true from several expressions. The
signature of JavaScript if else if statement is given below.

1. if(expression1){  
2. //content to be evaluated if expression1 is true  
3. }  
4. else if(expression2){  
5. //content to be evaluated if expression2 is true  
6. }  
7. else if(expression3){  
8. //content to be evaluated if expression3 is true  
9. }  
10. else{  
11. //content to be evaluated if no expression is true  
12. }  

Let’s see the simple example of if else if statement in javascript.

1. <script>  
2. var a=20;  
3. if(a==10){  
4. document.write("a is equal to 10");  
5. }  
6. else if(a==15){  
7. document.write("a is equal to 15");  
8. }  
9. else if(a==20){  
10. document.write("a is equal to 20");  
11. }  
12. else{  
13. document.write("a is not equal to 10, 15 or 20");  
14. }  
15. </script>  

JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple
expressions. It is just like else if statement that we have learned in previous page. But it
is convenient than if..else..if because it can be used with numbers, characters etc.

The signature of JavaScript switch statement is given below.

1. switch(expression){  
2. case value1:  
3.  code to be executed;  
4.  break;  
5. case value2:  
6.  code to be executed;  
7.  break;  
8. ......  
9.   
10. default:   
11.  code to be executed if above values are not matched;  
12. }  

Let’s see the simple example of switch statement in javascript.

1. <script>  
2. var grade='B';  
3. var result;  
4. switch(grade){  
5. case 'A':  
6. result="A Grade";  
7. break;  
8. case 'B':  
9. result="B Grade";  
10. break;  
11. case 'C':  
12. result="C Grade";  
13. break;  
14. default:  
15. result="No Grade";  
16. }  
17. document.write(result);  
18. </script>  
Test it Now

Output of the above example


B Grade

The switch statement is fall-through i.e. all the cases will be evaluated if you don't use
break statement.

Let’s understand the behaviour of switch statement in JavaScript.

1. <script>  
2. var grade='B';  
3. var result;  
4. switch(grade){  
5. case 'A':  
6. result+=" A Grade";  
7. case 'B':  
8. result+=" B Grade";  
9. case 'C':  
10. result+=" C Grade";  
11. default:  
12. result+=" No Grade";  
13. }  
14. document.write(result);  
15. </script>  

JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or
for-in loops. It makes the code compact. It is mostly used in array.
There are four types of loops in JavaScript.

1. for loop

2. while loop

3. do-while loop

4. for-in loop

1) JavaScript For loop


The JavaScript for loop iterates the elements for the fixed number of times. It should
be used if number of iteration is known. The syntax of for loop is given below.

1. for (initialization; condition; increment)  
2. {  
3.     code to be executed  
4. }  

Let’s see the simple example of for loop in javascript.

1. <script>  
2. for (i=1; i<=5; i++)  
3. {  
4. document.write(i + "<br/>")  
5. }  
6. </script>  
Test it Now

Output:

1
2
3
4
5

2) JavaScript while loop


The JavaScript while loop iterates the elements for the infinite number of times. It
should be used if number of iteration is not known. The syntax of while loop is given
below.

1. while (condition)  
2. {  
3.     code to be executed  
4. }  

Let’s see the simple example of while loop in javascript.

1. <script>  
2. var i=11;  
3. while (i<=15)  
4. {  
5. document.write(i + "<br/>");  
6. i++;  
7. }  
8. </script>  
Test it Now

Output:

11
12
13
14
15

3) JavaScript do while loop


The JavaScript do while loop iterates the elements for the infinite number of
times like while loop. But, code is executed at leastonce whether condition is true or
false. The syntax of do while loop is given below.

1. do{  
2.     code to be executed  
3. }while (condition);  

Let’s see the simple example of do while loop in javascript.

1. <script>  
2. var i=21;  
3. do{  
4. document.write(i + "<br/>");  
5. i++;  
6. }while (i<=25);  
7. </script>  
Test it Now

Output:

21
22
23
24
25

4) JavaScript for in loop


The JavaScript for in loop is used to iterate the properties of an object. We will discuss
about it later.

JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function
many times to reuse the code.

Advantage of JavaScript function


There are mainly two advantages of JavaScript functions.

1. Code reusability: We can call a function several times so it save coding.

2. Less coding: It makes our program compact. We don’t need to write many lines
of code each time to perform a common task.

JavaScript Function Syntax


The syntax of declaring function is given below.

1. function functionName([arg1, arg2, ...argN]){  
2.  //code to be executed  
3. }  

JavaScript Functions can have 0 or more arguments.


JavaScript Function Example
Let’s see the simple example of function in JavaScript that does not has arguments.

1. <script>  
2. function msg(){  
3. alert("hello! this is message");  
4. }  
5. </script>  
6. <input type="button" onclick="msg()" value="call function"/>  
Test it Now

Output of the above example

JavaScript Function Arguments


We can call function by passing arguments. Let’s see the example of function that has
one argument.

1. <script>  
2. function getcube(number){  
3. alert(number*number*number);  
4. }  
5. </script>  
6. <form>  
7. <input type="button" value="click" onclick="getcube(4)"/>  
8. </form>  
Test it Now

Output of the above example

Function with Return Value


We can call function that returns a value and use it in our program. Let’s see the
example of function that returns value.

1. <script>  
2. function getInfo(){  
3. return "hello javatpoint! How r u?";  
4. }  
5. </script>  
6. <script>  
7. document.write(getInfo());  
8. </script>  
Test it Now

Output of the above example


hello javatpoint! How r u?

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

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

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

Creating Objects in JavaScript


There are 3 ways to create objects.

1. By object literal

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

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

1) JavaScript Object by object literal


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

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

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

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

1. <script>  
2. emp={id:102,name:"Shyam Kumar",salary:40000}  
3. document.write(emp.id+" "+emp.name+" "+emp.salary);  
4. </script>  
Test it Now

Output of the above example


102 Shyam Kumar 40000

2) By creating instance of Object


The syntax of creating object directly is given below:

1. var objectname=new Object();  

Here, new keyword is used to create object.

Let’s see the example of creating object directly.

1. <script>  
2. var emp=new Object();  
3. emp.id=101;  
4. emp.name="Ravi Malik";  
5. emp.salary=50000;  
6. document.write(emp.id+" "+emp.name+" "+emp.salary);  
7. </script>  
Test it Now

Output of the above example


101 Ravi 50000

3) By using an Object constructor


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

The this keyword refers to the current object.

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

1. <script>  
2. function emp(id,name,salary){  
3. this.id=id;  
4. this.name=name;  
5. this.salary=salary;  
6. }  
7. e=new emp(103,"Vimal Jaiswal",30000);  
8.   
9. document.write(e.id+" "+e.name+" "+e.salary);  
10. </script>  
Test it Now

Output of the above example


103 Vimal Jaiswal 30000

Defining method in JavaScript Object


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

The example of defining method in object is given below.

1. <script>  
2. function emp(id,name,salary){  
3. this.id=id;  
4. this.name=name;  
5. this.salary=salary;  
6.   
7. this.changeSalary=changeSalary;  
8. function changeSalary(otherSalary){  
9. this.salary=otherSalary;  
10. }  
11. }  
12. e=new emp(103,"Sonoo Jaiswal",30000);  
13. document.write(e.id+" "+e.name+" "+e.salary);  
14. e.changeSalary(45000);  
15. document.write("<br>"+e.id+" "+e.name+" "+e.salary);  
16. </script>  
Test it Now

Output of the above example


103 Sonoo Jaiswal 30000
103 Sonoo Jaiswal 45000
JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.

There are 3 ways to construct array in JavaScript

1. By array literal

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

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

1) JavaScript array literal


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

1. var arrayname=[value1,value2.....valueN];  

As you can see, values are contained inside [ ] and separated by , (comma).

Let’s see the simple example of creating and using array in JavaScript.

1. <script>  
2. var emp=["Sonoo","Vimal","Ratan"];  
3. for (i=0;i<emp.length;i++){  
4. document.write(emp[i] + "<br/>");  
5. }  
6. </script>  
Test it Now

The .length property returns the length of an array.

Output of the above example


Sonoo
Vimal
Ratan

2) JavaScript Array directly (new keyword)


The syntax of creating array directly is given below:

1. var arrayname=new Array();  
Here, new keyword is used to create instance of array.

Let’s see the example of creating array directly.

1. <script>  
2. var i;  
3. var emp = new Array();  
4. emp[0] = "Arun";  
5. emp[1] = "Varun";  
6. emp[2] = "John";  
7.   
8. for (i=0;i<emp.length;i++){  
9. document.write(emp[i] + "<br>");  
10. }  
11. </script>  
Test it Now

Output of the above example


Arun
Varun
John

3) JavaScript array constructor (new keyword)


Here, you need to create instance of array by passing arguments in constructor so that
we don't have to provide value explicitly.

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

1. <script>  
2. var emp=new Array("Jai","Vijay","Smith");  
3. for (i=0;i<emp.length;i++){  
4. document.write(emp[i] + "<br>");  
5. }  
6. </script>  
Test it Now

Output of the above example


Jai
Vijay
Smith
JavaScript String
The JavaScript string is an object that represents a sequence of characters.

There are 2 ways to create string in JavaScript

1. By string literal

2. By string object (using new keyword)

1) By string literal
The string literal is created using double quotes. The syntax of creating string using
string literal is given below:

1. var stringname="string value";  

Let’s see the simple example of creating string literal.

1. <script>  
2. var str="This is string literal";  
3. document.write(str);  
4. </script>  
Test it Now

Output:

This is string literal

2) By string object (using new keyword)


The syntax of creating string object using new keyword is given below:

1. var stringname=new String("string literal");  

Here, new keyword is used to create instance of string.

Let’s see the example of creating string in JavaScript by new keyword.


1. <script>  
2. var stringname=new String("hello javascript string");  
3. document.write(stringname);  
4. </script>  
Test it Now

Output:

hello javascript string

JavaScript String Methods


Let's see the list of JavaScript string methods with examples.

o charAt(index)

o concat(str)

o indexOf(str)

o lastIndexOf(str)

o toLowerCase()

o toUpperCase()

o slice(beginIndex, endIndex)

o trim()

1) JavaScript String charAt(index) Method


The JavaScript String charAt() method returns the character at the given index.

1. <script>  
2. var str="javascript";  
3. document.write(str.charAt(2));  
4. </script>  
Test it Now

Output:

v
2) JavaScript String concat(str) Method
The JavaScript String concat(str) method concatenates or joins two strings.

1. <script>  
2. var s1="javascript ";  
3. var s2="concat example";  
4. var s3=s1.concat(s2);  
5. document.write(s3);  
6. </script>  
Test it Now

Output:

javascript concat example

3) JavaScript String indexOf(str) Method


The JavaScript String indexOf(str) method returns the index position of the given string.

1. <script>  
2. var s1="javascript from javatpoint indexof";  
3. var n=s1.indexOf("from");  
4. document.write(n);  
5. </script>  
Test it Now

Output:

11

4) JavaScript String lastIndexOf(str) Method


The JavaScript String lastIndexOf(str) method returns the last index position of the given
string.

1. <script>  
2. var s1="javascript from javatpoint indexof";  
3. var n=s1.lastIndexOf("java");  
4. document.write(n);  
5. </script>  
Test it Now

Output:

16
5) JavaScript String toLowerCase() Method
The JavaScript String toLowerCase() method returns the given string in lowercase
letters.

1. <script>  
2. var s1="JavaScript toLowerCase Example";  
3. var s2=s1.toLowerCase();  
4. document.write(s2);  
5. </script>  
Test it Now

Output:

javascript tolowercase example

6) JavaScript String toUpperCase() Method


The JavaScript String toUpperCase() method returns the given string in uppercase
letters.

1. <script>  
2. var s1="JavaScript toUpperCase Example";  
3. var s2=s1.toUpperCase();  
4. document.write(s2);  
5. </script>  
Test it Now

Output:

JAVASCRIPT TOUPPERCASE EXAMPLE

7) JavaScript String slice(beginIndex, endIndex) Method


The JavaScript String slice(beginIndex, endIndex) method returns the parts of string
from given beginIndex to endIndex. In slice() method, beginIndex is inclusive and
endIndex is exclusive.

1. <script>  
2. var s1="abcdefgh";  
3. var s2=s1.slice(2,5);  
4. document.write(s2);  
5. </script>  
Test it Now

Output:
cde

8) JavaScript String trim() Method


The JavaScript String trim() method removes leading and trailing whitespaces from the
string.

1. <script>  
2. var s1="     javascript trim    ";  
3. var s2=s1.trim();  
4. document.write(s2);  
5. </script>  
Test it Now

Output:

javascript trim

JavaScript Date Object


The JavaScript date object can be used to get year, month and day. You can display a
timer on the webpage by the help of JavaScript date object.

You can use different Date constructors to create date object. It provides methods to get
and set day, month, year, hour, minute and seconds.

Constructor
You can use 4 variant of Date constructor to create date object.

1. Date()  
2. Date(milliseconds)  
3. Date(dateString)  
4. Date(year, month, day, hours, minutes, seconds, milliseconds)  

JavaScript Date Methods


The important methods of date object are as follows:

Method Description
getFullYear() returns the year in 4 digit e.g. 2015. It is a new method and
suggested than getYear() which is now deprecated.

getMonth() returns the month in 2 digit from 0 to 11. So it is better to use


getMonth()+1 in your code.

getDate() returns the date in 1 or 2 digit from 1 to 31.

getDay() returns the day of week in 1 digit from 0 to 6.

getHours() returns all the elements having the given name value.

getMinutes() returns all the elements having the given class name.

getSeconds() returns all the elements having the given class name.

getMilliseconds( returns all the elements having the given tag name.
)

JavaScript Date Example


Let's see the simple example to print date object. It prints date and time both.

1. Current Date and Time: <span id="txt"></span>  
2. <script>  
3. var today=new Date();  
4. document.getElementById('txt').innerHTML=today;  
5. </script>  
Test it Now

Output:

Current Date and Time: Sat Jan 27 2018 14:56:23 GMT+0530 (India Standard Time)

Let's see another code to print date/month/year.

1. <script>  
2. var date=new Date();  
3. var day=date.getDate();  
4. var month=date.getMonth()+1;  
5. var year=date.getFullYear();  
6. document.write("<br>Date is: "+day+"/"+month+"/"+year);  
7. </script>  

Output:

Date is: 27/1/2018

JavaScript Current Time Example


Let's see the simple example to print current time of system.

1. Current Time: <span id="txt"></span>  
2. <script>  
3. var today=new Date();  
4. var h=today.getHours();  
5. var m=today.getMinutes();  
6. var s=today.getSeconds();  
7. document.getElementById('txt').innerHTML=h+":"+m+":"+s;  
8. </script>  
Test it Now

Output:

Current Time: 14:56:23

JavaScript Digital Clock Example


Let's see the simple example to display digital clock using JavaScript date object.

There are two ways to set interval in JavaScript: by setTimeout() or setInterval()


method.

1. Current Time: <span id="txt"></span>  
2. <script>  
3. window.onload=function(){getTime();}  
4. function getTime(){  
5. var today=new Date();  
6. var h=today.getHours();  
7. var m=today.getMinutes();  
8. var s=today.getSeconds();  
9. // add a zero in front of numbers<10  
10. m=checkTime(m);  
11. s=checkTime(s);  
12. document.getElementById('txt').innerHTML=h+":"+m+":"+s;  
13. setTimeout(function(){getTime()},1000);  
14. }  
15. //setInterval("getTime()",1000);//another way  
16. function checkTime(i){  
17. if (i<10){  
18.   i="0" + i;  
19.  }  
20. return i;  
21. }  
22. </script>  
Test it Now

Output:

Current Time:  14:57:08

JavaScript Math Object


The JavaScript math object provides several constants and methods to perform
mathematical operation. Unlike date object, it doesn't have constructors.

Math.sqrt(n)
The JavaScript math.sqrt(n) method returns the square root of the given number.

1. Square Root of 17 is: <span id="p1"></span>    
2. <script>    
3. document.getElementById('p1').innerHTML=Math.sqrt(17);    
4. </script>    
Test it Now

Output:

Square Root of 17 is: 4.123105625617661

Math.random()
The JavaScript math.random() method returns the random number between 0 to 1.

1. Random Number is: <span id="p2"></span>    
2. <script>    
3. document.getElementById('p2').innerHTML=Math.random();    
4. </script>   
Test it Now

Output:

Random Number is: 0.848798670503172

Math.pow(m,n)
The JavaScript math.pow(m,n) method returns the m to the power of n that is mn.

1. 3 to the power of 4 is: <span id="p3"></span>    
2. <script>    
3. document.getElementById('p3').innerHTML=Math.pow(3,4);    
4. </script>    
Test it Now

Output:

3 to the power of 4 is: 81

Math.floor(n)
The JavaScript math.floor(n) method returns the lowest integer for the given number.
For example 3 for 3.7, 5 for 5.9 etc.

1. Floor of 4.6 is: <span id="p4"></span>    
2. <script>    
3. document.getElementById('p4').innerHTML=Math.floor(4.6);    
4. </script>    
Test it Now

Output:

Floor of 4.6 is: 4

Math.ceil(n)
The JavaScript math.ceil(n) method returns the largest integer for the given number. For
example 4 for 3.7, 6 for 5.9 etc.
1. Ceil of 4.6 is: <span id="p5"></span>    
2. <script>    
3. document.getElementById('p5').innerHTML=Math.ceil(4.6);    
4. </script>    
Test it Now

Output:

Ceil of 4.6 is: 5

Math.round(n)
The JavaScript math.round(n) method returns the rounded integer nearest for the given
number. If fractional part is equal or greater than 0.5, it goes to upper value 1 otherwise
lower value 0. For example 4 for 3.7, 3 for 3.3, 6 for 5.9 etc.

1. Round of 4.3 is: <span id="p6"></span><br>    
2. Round of 4.7 is: <span id="p7"></span>    
3. <script>    
4. document.getElementById('p6').innerHTML=Math.round(4.3);   
5. document.getElementById('p7').innerHTML=Math.round(4.7);    
6. </script>    
Test it Now

Output:

Round of 4.3 is: 4 


Round of 4.7 is: 5

Math.abs(n)
The JavaScript math.abs(n) method returns the absolute value for the given number. For
example 4 for -4, 6.6 for -6.6 etc.

1. Absolute value of -4 is: <span id="p8"></span>      
2. <script>      
3. document.getElementById('p8').innerHTML=Math.abs(-4);      
4. </script>   
Test it Now

Output:

Absolute value of -4 is: 4

JavaScript Number Object


The JavaScript number object enables you to represent a numeric value. It may be
integer or floating-point. JavaScript number object follows IEEE standard to represent
the floating-point numbers.

By the help of Number() constructor, you can create number object in JavaScript. For
example:

1. var n=new Number(value);  

If value can't be converted to number, it returns NaN(Not a Number) that can be


checked by isNaN() method.

You can direct assign a number to a variable also. For example:

1. var x=102;//integer value  
2. var y=102.7;//floating point value  
3. var z=13e4;//exponent value, output: 130000  
4. var n=new Number(16);//integer value by number object  
Test it Now

Output:

102 102.7 130000 16

JavaScript Number Constants


Let's see the list of JavaScript number constants with description.

Constant Description

MIN_VALUE returns the largest minimum value.

MAX_VALUE returns the largest maximum value.

POSITIVE_INFINITY returns positive infinity, overflow value.

NEGATIVE_INFINITY returns negative infinity, overflow value.

NaN represents "Not a Number" value.

JavaScript Number Methods


Let's see the list of JavaScript number methods with description.

Methods Description

toExponential(x displays exponential value.


)

toFixed(x) limits the number of digits after decimal value.

toPrecision(x) formats the number with given number of digits.

toString() converts number into string.

valueOf() coverts other type of value into number.

JavaScript Boolean
JavaScript Boolean is an object that represents value in two states: true or false. You
can create the JavaScript Boolean object by Boolean() constructor as given below.

1. Boolean b=new Boolean(value);  

The default value of JavaScript Boolean object is false.

JavaScript Boolean Example


1. <script>  
2. document.write(10<20);//true  
3. document.write(10<5);//false  
4. </script>  

JavaScript Boolean Properties

Property Description

constructo returns the reference of Boolean function that created Boolean object.
r
prototype enables you to add properties and methods in Boolean prototype.

JavaScript Boolean Methods

Method Description

toSource() returns the source of Boolean object as a string.

toString() converts Boolean into String.

valueOf() converts other type into Boolean.

Browser Object Model


1. Browser Object Model (BOM)

The Browser Object Model (BOM) is used to interact with the browser.

The default object of browser is window means you can call all the functions of window
by specifying window or directly. For example:

1. window.alert("hello javatpoint");  

is same as:

1. alert("hello javatpoint");  

You can use a lot of properties (other objects) defined underneath the window object like
document, history, screen, navigator, location, innerHeight, innerWidth,

Note: The document object represents an html document. It forms DOM (Document Object
Model).
Visit the next page to learn about window object fully with example.

Window Object
1. Window Object
2. Properties of Window Object
3. Methods of Window Object
4. Example of Window Object

The window object represents a window in browser. An object of window is created


automatically by the browser.

Window is the object of browser, it is not the object of javascript. The javascript
objects are string, array, date etc.

Note: if html document contains frame or iframe, browser creates additional window
objects for each frame.

Methods of window object


The important methods of window object are as follows:

Method Description
alert() displays the alert box containing message with ok button.

confirm() displays the confirm dialog box containing message with ok and
cancel button.

prompt() displays a dialog box to get input from the user.

open() opens the new window.

close() closes the current window.

setTimeout( performs action after specified time like calling function, evaluating
) expressions etc.

Example of alert() in javascript


It displays alert dialog box. It has message and ok button.

1. <script type="text/javascript">  
2. function msg(){  
3.  alert("Hello Alert Box");  
4. }  
5. </script>  
6. <input type="button" value="click" onclick="msg()"/>  

Output of the above example

Example of confirm() in javascript


It displays the confirm dialog box. It has message with ok and cancel buttons.

1. <script type="text/javascript">  
2. function msg(){  
3. var v= confirm("Are u sure?");  
4. if(v==true){  
5. alert("ok");  
6. }  
7. else{  
8. alert("cancel");  
9. }  
10.   
11. }  
12. </script>  
13.   
14. <input type="button" value="delete record" onclick="msg()"/>  

Output of the above example

Example of prompt() in javascript


It displays prompt dialog box for input. It has message and textfield.

1. <script type="text/javascript">  
2. function msg(){  
3. var v= prompt("Who are you?");  
4. alert("I am "+v);  
5.   
6. }  
7. </script>  
8.   
9. <input type="button" value="click" onclick="msg()"/>  

Output of the above example

Example of open() in javascript


It displays the content in a new window.

1. <script type="text/javascript">  
2. function msg(){  
3. open("http://www.javatpoint.com");  
4. }  
5. </script>  
6. <input type="button" value="javatpoint" onclick="msg()"/>  

Output of the above example

Example of setTimeout() in javascript


It performs its task after the given milliseconds.

1. <script type="text/javascript">  
2. function msg(){  
3. setTimeout(  
4. function(){  
5. alert("Welcome to Javatpoint after 2 seconds")  
6. },2000);  
7.   
8. }  
9. </script>  
10.   
11. <input type="button" value="click" onclick="msg()"/>  

JavaScript History Object


1. History Object
2. Properties of History Object
3. Methods of History Object
4. Example of History Object

The JavaScript history object represents an array of URLs visited by the user. By


using this object, you can load previous, forward or any particular page.

The history object is the window property, so it can be accessed by:


1. window.history  

Or,

1. history  

Property of JavaScript history object


There are only 1 property of history object.

No. Property Description

1 length returns the length of the history URLs.

Methods of JavaScript history object


There are only 3 methods of history object.

No Method Description
.

1 forward() loads the next page.

2 back() loads the previous page.

3 go() loads the given page number.

Example of history object


Let’s see the different usage of history object.
1. history.back();//for previous page  
2. history.forward();//for next page  
3. history.go(2);//for next 2nd page  
4. history.go(-2);//for previous 2nd page  

JavaScript Navigator Object


1. Navigator Object
2. Properties of Navigator Object
3. Methods of Navigator Object
4. Example of Navigator Object

The JavaScript navigator object is used for browser detection. It can be used to get
browser information such as appName, appCodeName, userAgent etc.

The navigator object is the window property, so it can be accessed by:

1. window.navigator  

Or,

1. navigator  

Property of JavaScript navigator object


There are many properties of navigator object that returns information of the browser.

No. Property Description

1 appName returns the name

2 appVersion returns the version

3 appCodeName returns the code name

4 cookieEnabled returns true if cookie is enabled otherwise false

5 userAgent returns the user agent


6 language returns the language. It is supported in Netscape and
Firefox only.

7 userLanguage returns the user language. It is supported in IE only.

8 plugins returns the plugins. It is supported in Netscape and


Firefox only.

9 systemLanguag returns the system language. It is supported in IE only.


e

10 mimeTypes[] returns the array of mime type. It is supported in


Netscape and Firefox only.

11 platform returns the platform e.g. Win32.

12 online returns true if browser is online otherwise false.

Methods of JavaScript navigator object


The methods of navigator object are given below.

No Method Description
.

1 javaEnabled() checks if java is enabled.

2 taintEnabled() checks if taint is enabled. It is deprecated since JavaScript


1.2.

Example of navigator object


Let’s see the different usage of history object.

1. <script>  
2. document.writeln("<br/>navigator.appCodeName: "+navigator.appCodeName);  
3. document.writeln("<br/>navigator.appName: "+navigator.appName);  
4. document.writeln("<br/>navigator.appVersion: "+navigator.appVersion);  
5. document.writeln("<br/>navigator.cookieEnabled: "+navigator.cookieEnabled);  
6. document.writeln("<br/>navigator.language: "+navigator.language);  
7. document.writeln("<br/>navigator.userAgent: "+navigator.userAgent);  
8. document.writeln("<br/>navigator.platform: "+navigator.platform);  
9. document.writeln("<br/>navigator.onLine: "+navigator.onLine);  
10. </script>  
Test it Now

navigator.appCodeName: Mozilla
navigator.appName: Netscape
navigator.appVersion: 5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
navigator.cookieEnabled: true
navigator.language: en-US
navigator.userAgent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
navigator.platform: Win32
navigator.onLine: true

JavaScript Screen Object


1. Screen Object
2. Properties of Screen Object
3. Methods of Screen Object
4. Example of Screen Object

The JavaScript screen object holds information of browser screen. It can be used to


display screen width, height, colorDepth, pixelDepth etc.

The navigator object is the window property, so it can be accessed by:

1. window.screen  

Or,

1. screen  

Property of JavaScript Screen Object


There are many properties of screen object that returns information of the browser.
No Property Description
.

1 width returns the width of the screen

2 height returns the height of the screen

3 availWidth returns the available width

4 availHeigh returns the available height


t

5 colorDepth returns the color depth

6 pixelDepth returns the pixel depth.

Example of JavaScript Screen Object


Let’s see the different usage of screen object.

1. <script>  
2. document.writeln("<br/>screen.width: "+screen.width);  
3. document.writeln("<br/>screen.height: "+screen.height);  
4. document.writeln("<br/>screen.availWidth: "+screen.availWidth);  
5. document.writeln("<br/>screen.availHeight: "+screen.availHeight);  
6. document.writeln("<br/>screen.colorDepth: "+screen.colorDepth);  
7. document.writeln("<br/>screen.pixelDepth: "+screen.pixelDepth);  
8. </script>  
Test it Now

screen.width: 1366
screen.height: 768
screen.availWidth: 1366
screen.availHeight: 728
screen.colorDepth: 24
screen.pixelDepth: 24

Document Object Model


1. Document Object
2. Properties of document object
3. Methods of document object
4. Example of document object

The document object represents the whole html document.

When html document is loaded in the browser, it becomes a document object. It is


the root element that represents the html document. It has properties and methods.
By the help of document object, we can add dynamic content to our web page.

As mentioned earlier, it is the object of window. So

1. window.document  

Is same as

1. document  

According to W3C - "The W3C Document Object Model (DOM) is a platform and
language-neutral interface that allows programs and scripts to dynamically access and
update the content, structure, and style of a document."

Properties of document object


Let's see the properties of document object that can be accessed and modified by the
document
object. 

Methods of document object


We can access and change the contents of document by its methods.

The important methods of document object are as follows:


Method Description

write("string") writes the given string on the doucment.

writeln("string") writes the given string on the doucment with newline


character at the end.

getElementById() returns the element having the given id value.

getElementsByName() returns all the elements having the given name value.

getElementsByTagName() returns all the elements having the given tag name.

getElementsByClassName( returns all the elements having the given class name.
)

Accessing field value by document object


In this example, we are going to get the value of input text by user. Here, we are
using document.form1.name.value to get the value of name field.

Here, document is the root element that represents the html document.

form1 is the name of the form.

name is the attribute name of the input text.

value is the property, that returns the value of the input text.

Let's see the simple example of document object that prints name with welcome
message.

1. <script type="text/javascript">  
2. function printvalue(){  
3. var name=document.form1.name.value;  
4. alert("Welcome: "+name);  
5. }  
6. </script>  
7.   
8. <form name="form1">  
9. Enter Name:<input type="text" name="name"/>  
10. <input type="button" onclick="printvalue()" value="print name"/>  
11. </form>  

Javascript -document.getElementById()
method
1. getElementById() method
2. Example of getElementById()

The document.getElementById() method returns the element of specified id.

In the previous page, we have used document.form1.name.value to get the value of


the input value. Instead of this, we can use document.getElementById() method to get
value of the input text. But we need to define id for the input field.

Let's see the simple example of document.getElementById() method that prints cube of
the given number.

1. <script type="text/javascript">  
2. function getcube(){  
3. var number=document.getElementById("number").value;  
4. alert(number*number*number);  
5. }  
6. </script>  
7. <form>  
8. Enter No:<input type="text" id="number" name="number"/><br/>  
9. <input type="button" value="cube" onclick="getcube()"/>  
10. </form>  

Output of the above example

Enter No:

Javascript - document.getElementsByName()
method
1. getElementsByName() method
2. Example of getElementsByName()

The document.getElementsByName() method returns all the element of specified


name.

The syntax of the getElementsByName() method is given below:

1. document.getElementsByName("name")  

Here, name is required.

Example of document.getElementsByName() method


In this example, we going to count total number of genders. Here, we are using
getElementsByName() method to get all the genders.

1. <script type="text/javascript">  
2. function totalelements()  
3. {  
4. var allgenders=document.getElementsByName("gender");  
5. alert("Total Genders:"+allgenders.length);  
6. }  
7. </script>  
8. <form>  
9. Male:<input type="radio" name="gender" value="male">  
10. Female:<input type="radio" name="gender" value="female">  
11.   
12. <input type="button" onclick="totalelements()" value="Total Genders">  
13. </form>  

Output of the above example

Male:  Female:  

Javascript -
document.getElementsByTagName() method
1. getElementsByTagName() method
2. Example of getElementsByTagName()
The document.getElementsByTagName() method returns all the element of specified
tag name.

The syntax of the getElementsByTagName() method is given below:

1. document.getElementsByTagName("name")  

Here, name is required.

Example of document.getElementsByTagName() method


In this example, we going to count total number of paragraphs used in the document. To
do this, we have called the document.getElementsByTagName("p") method that returns
the total paragraphs.

1. <script type="text/javascript">  
2. function countpara(){  
3. var totalpara=document.getElementsByTagName("p");  
4. alert("total p tags are: "+totalpara.length);  
5.   
6. }  
7. </script>  
8. <p>This is a pragraph</p>  
9. <p>Here we are going to count total number of paragraphs by getElementByTag
Name() method.</p>  
10. <p>Let's see the simple example</p>  
11. <button onclick="countpara()">count paragraph</button>  

Output of the above example


This is a pragraph

Here we are going to count total number of paragraphs by getElementByTagName()


method.

Let's see the simple example

count paragraph

Another example of
document.getElementsByTagName() method
In this example, we going to count total number of h2 and h3 tags used in the
document.

1. <script type="text/javascript">  
2. function counth2(){  
3. var totalh2=document.getElementsByTagName("h2");  
4. alert("total h2 tags are: "+totalh2.length);  
5. }  
6. function counth3(){  
7. var totalh3=document.getElementsByTagName("h3");  
8. alert("total h3 tags are: "+totalh3.length);  
9. }  
10. </script>  
11. <h2>This is h2 tag</h2>  
12. <h2>This is h2 tag</h2>  
13. <h3>This is h3 tag</h3>  
14. <h3>This is h3 tag</h3>  
15. <h3>This is h3 tag</h3>  
16. <button onclick="counth2()">count h2</button>  
17. <button onclick="counth3()">count h3</button>  

Output of the above example

This is h2 tag
This is h2 tag
This is h3 tag

This is h3 tag

This is h3 tag
count h2 count h3

Javascript - innerHTML
1. javascript innerHTML
2. Example of innerHTML property

The innerHTML property can be used to write the dynamic html on the html document.
It is used mostly in the web pages to generate the dynamic html such as registration
form, comment form, links etc.

Example of innerHTML property


In this example, we are going to create the html form when user clicks on the button.

In this example, we are dynamically writing the html form inside the div name having
the id mylocation. We are identifing this position by calling the
document.getElementById() method.

1. <script type="text/javascript" >  
2. function showcommentform() {  
3. var data="Name:<input type='text' name='name'><br>Comment:<br><text
area rows='5' cols='80'></textarea>  
4. <br><input type='submit' value='Post Comment'>";  
5. document.getElementById('mylocation').innerHTML=data;  
6. }  
7. </script>  
8. <form name="myForm">  
9. <input type="button" value="comment" onclick="showcommentform()">  
10. <div id="mylocation"></div>  
11. </form>  
Test it Now

Output of the above example

Javascript - innerText
1. javascript innerText
2. Example of innerText property
The innerText property can be used to write the dynamic text on the html document.
Here, text will not be interpreted as html text but a normal text.

It is used mostly in the web pages to generate the dynamic content such as writing the
validation message, password strength etc.

Javascript innerText Example


In this example, we are going to display the password strength when releases the key
after press.

1. <script type="text/javascript" >  
2. function validate() {  
3. var msg;  
4. if(document.myForm.userPass.value.length>5){  
5. msg="good";  
6. }  
7. else{  
8. msg="poor";  
9. }  
10. document.getElementById('mylocation').innerText=msg;  
11.  }  
12.   
13. </script>  
14. <form name="myForm">  
15. <input type="password" value="" name="userPass" onkeyup="validate()">  
16. Strength:<span id="mylocation">no strength</span>  
17. </form>  
Test it Now

Output of the above example

 Strength:no strength

Show/Hide Comment Form Example using


innerHTML
1. <!DOCTYPE html>  
2. <html>  
3. <head>  
4. <title>First JS</title>  
5. <script>  
6. var flag=true;  
7. function commentform(){  
8. var cform="<form action='Comment'>Enter Name:<br><input type='text' na
me='name'/><br/>  
9. Enter Email:<br><input type='email' name='email'/><br>Enter Comment:<b
r/>  
10. <textarea rows='5' cols='70'></textarea><br><input type='submit' value='
Post Comment'/></form>";  
11. if(flag){  
12. document.getElementById("mylocation").innerHTML=cform;  
13. flag=false;  
14. }else{  
15. document.getElementById("mylocation").innerHTML="";  
16. flag=true;  
17. }  
18. }  
19. </script>  
20. </head>  
21. <body>  
22. <button onclick="commentform()">Comment</button>  
23. <div id="mylocation"></div>  
24. </body>  
25. </html>  

JavaScript Form Validation


1. JavaScript form validation
2. Example of JavaScript validation
3. JavaScript email validation

It is important to validate the form submitted by the user because it can have
inappropriate values. So validation is must.

The JavaScript provides you the facility the validate the form on the client side so
processing will be fast than server-side validation. So, most of the web developers prefer
JavaScript form validation.
Through JavaScript, we can validate name, password, email, date, mobile number etc
fields.

JavaScript form validation example


In this example, we are going to validate the name and password. The name can’t be
empty and password can’t be less than 6 characters long.

Here, we are validating the form on form submit. The user will not be forwarded to the
next page until given values are correct.

1. <script>  
2. function validateform(){  
3. var name=document.myform.name.value;  
4. var password=document.myform.password.value;  
5.   
6. if (name==null || name==""){  
7.   alert("Name can't be blank");  
8.   return false;  
9. }else if(password.length<6){  
10.   alert("Password must be at least 6 characters long.");  
11.   return false;  
12.   }  
13. }  
14. </script>  
15. <body>  
16. <form name="myform" method="post" action="abc.jsp" onsubmit="return valid
ateform()" >  
17. Name: <input type="text" name="name"><br/>  
18. Password: <input type="password" name="password"><br/>  
19. <input type="submit" value="register">  
20. </form>  
Test it Now

JavaScript Retype Password Validation


1. <script type="text/javascript">  
2. function matchpass(){  
3. var firstpassword=document.f1.password.value;  
4. var secondpassword=document.f1.password2.value;  
5.   
6. if(firstpassword==secondpassword){  
7. return true;  
8. }  
9. else{  
10. alert("password must be same!");  
11. return false;  
12. }  
13. }  
14. </script>  
15.   
16. <form name="f1" action="register.jsp" onsubmit="return matchpass()">  
17. Password:<input type="password" name="password" /><br/>  
18. Re-enter Password:<input type="password" name="password2"/><br/>  
19. <input type="submit">  
20. </form>  
Test it Now

JavaScript Number Validation


Let's validate the textfield for numeric value only. Here, we are using isNaN() function.

1. <script>  
2. function validate(){  
3. var num=document.myform.num.value;  
4. if (isNaN(num)){  
5.   document.getElementById("numloc").innerHTML="Enter Numeric value only";  
6.   return false;  
7. }else{  
8.   return true;  
9.   }  
10. }  
11. </script>  
12. <form name="myform" onsubmit="return validate()" >  
13. Number: <input type="text" name="num"><span id="numloc"></span><br
/>  
14. <input type="submit" value="submit">  
15. </form>  
Test it Now
JavaScript validation with image
Let’s see an interactive JavaScript form validation example that displays correct and
incorrect image if input is correct or incorrect.

1. <script>  
2. function validate(){  
3. var name=document.f1.name.value;  
4. var password=document.f1.password.value;  
5. var status=false;  
6.   
7. if(name.length<1){  
8. document.getElementById("nameloc").innerHTML=  
9. " <img src='unchecked.gif'/> Please enter your name";  
10. status=false;  
11. }else{  
12. document.getElementById("nameloc").innerHTML=" <img src='checked.gif'/>";  
13. status=true;  
14. }  
15. if(password.length<6){  
16. document.getElementById("passwordloc").innerHTML=  
17. " <img src='unchecked.gif'/> Password must be at least 6 char long";  
18. status=false;  
19. }else{  
20. document.getElementById("passwordloc").innerHTML=" <img src='checked.gif'/>
";  
21. }  
22. return status;  
23. }  
24. </script>  
25.   
26. <form name="f1" action="#" onsubmit="return validate()">  
27. <table>  
28. <tr><td>Enter Name:</td><td><input type="text" name="name"/>  
29. <span id="nameloc"></span></td></tr>  
30. <tr><td>Enter Password:</td><td><input type="password" name="passwo
rd"/>  
31. <span id="passwordloc"></span></td></tr>  
32. <tr><td colspan="2"><input type="submit" value="register"/></td></tr>  
33. </table>  
34. </form>  
Test it Now

Output:

Enter Name:

Enter Password:

register

JavaScript email validation


We can validate the email by the help of JavaScript.

There are many criteria that need to be follow to validate the email id such as:

o email id must contain the @ and . character

o There must be at least one character before and after the @.

o There must be at least two characters after . (dot).

Let's see the simple example to validate the email field.

1. <script>  
2. function validateemail()  
3. {  
4. var x=document.myform.email.value;  
5. var atposition=x.indexOf("@");  
6. var dotposition=x.lastIndexOf(".");  
7. if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){  
8.   alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposit
ion:"+dotposition);  
9.   return false;  
10.   }  
11. }  
12. </script>  
13. <body>  
14. <form name="myform"  method="post" action="#" onsubmit="return validatee
mail();">  
15. Email: <input type="text" name="email"><br/>  
16.   
17. <input type="submit" value="register">  
18. </form>  

HTML/DOM events for JavaScript


HTML or DOM events are widely used in JavaScript code. JavaScript code is executed
with HTML/DOM events. So before learning JavaScript, let’s have some idea about
events.

Events Description

onclick occurs when element is clicked.

ondblclick occurs when element is double-clicked.

onfocus occurs when an element gets focus such as button, input, textarea
etc.

onblur occurs when form looses the focus from an element.

onsubmit occurs when form is submitted.

onmouseover occurs when mouse is moved over an element.

onmouseout occurs when mouse is moved out from an element (after moved
over).

onmousedow occurs when mouse button is pressed over an element.


n

onmouseup occurs when mouse is released from an element (after mouse is


pressed).

onload occurs when document, object or frameset is loaded.

onunload occurs when body or frameset is unloaded.

onscroll occurs when document is scrolled.

onresized occurs when document is resized.

onreset occurs when form is reset.


onkeydown occurs when key is being pressed.

onkeypress occurs when user presses the key.

onkeyup occurs when key is released.

JavaScript Interview Questions


JavaScript interview questions and answers for provides a list of top 20 interview
questions. The frequently asked JavaScript interview questions with answers for
beginners and professionals are given below.

1) What is JavaScript?
JavaScript is a scripting language. It is different from Java language. It is object-based,
lightweight and cross platform. It is widely used for client side validation. More details...

2) What is the difference between JavaScript and jscript?


Netscape provided the JavaScript language. Microsoft changed the name and called it
JScript to avoid the trademark issue.In other words, you can say JScript is same as
JavaScript, but it is provided by Microsoft.

3) How to write a hello world example of JavaScript?


A simple example of JavaScript hello world is given below. You need to place it inside the
body tag of html.

1. <script type="text/javascript">  
2. document.write("JavaScript Hello World!");  
3. </script>  
More details...

4) How to use external JavaScript file?


I am assuming that js file name is message.js, place the following script tag inside the
head tag.

1. <script type="text/javascript" src="message.js"></script>  
More details...
5) Is JavaScript case sensitive language?
Yes.

6) What is BOM?
BOM stands for Browser Object Model. It provides interaction with the browser. The
default object of browser is window.

More Details: Browser Object Model

7) What is DOM? What is the use of document object?


DOM stands for Document Object Model. A document object represent the html
document. It can be used to access and change the content of html.

More Details: Document Object Model

8) What is the use of window object?


The window object is automatically created by the browser that represents a window of a
browser.

It is used to display the popup dialog box such as alert dialog box, confirm dialog box,
input dialog box etc.

More details...

9) What is the use of history object?


The history object of browser can be used to switch to history pages such as back and
forward from current page or another page. There are three methods of history object.

1. history.back()

2. history.forward()

3. history.go(number): number may be positive for forward, negative for backward.

More details...
10) How to write comment in JavaScript?
There are two types of comments in JavaScript.

1. Single Line Comment: It is represented by // (double forward slash)

2. Multi Line Comment: It is represented by slash with asterisk symbol as /* write


comment here */

More details...

11) How to create function in JavaScript?


To create function in JavaScript, follow the following syntax.

1. function function_name(){  
2. //function body  
3. }  
More details...

12) What are the JavaScript data types?


There are two types of data types in JavaScript:

1. Primitive Data Types

2. Non-primitive Data Types

More details...

13) What is the difference between == and ===?


The == operator checks equality only whereas === checks equality and data type i.e.
value must be of same type.

14) How to write html code dynamically using JavaScript?


The innerHTML property is used to write the HTML code using JavaScript dynamically.
Let's see a simple example:

1. document.getElementById('mylocation').innerHTML="<h2>This is heading using 
JavaScript</h2>";   
More details...
15) How to write normal text code using JavaScript
dynamically?
The innerText property is used to write the simple text using JavaScript dynamically.
Let's see a simple example:

1. document.getElementById('mylocation').innerText="This is text using JavaScript"
;   
More details...

16) How to create objects in JavaScript?


There are 3 ways to create object in JavaScript.

1. By object literal

2. By creating instance of Object

3. By Object Constructor

Let's see a simple code to create object using object literal.

1. emp={id:102,name:"Rahul Kumar",salary:50000}   
More details...

17) How to create array in JavaScript?


There are 3 ways to create array in JavaScript.

1. By array literal

2. By creating instance of Array

3. By using an Array constructor

Let's see a simple code to create array using object literal.

1. var emp=["Shyam","Vimal","Ratan"];    
More details...

18) What does the isNaN() function?


The isNan() function returns true if the variable value is not a number.
19) What is the output of 10+20+"30" in JavaScript?
3030 because 10+20 will be 30. If there is numeric value before and after +, it is
treated is binary + (arithmetic operator).

20) What is the output of "10"+20+30 in JavaScript?


102030 because after a string all the + will be treated as string concatenation operator
(not binary +).

21) Difference between Client side JavaScript and Server side


JavaScript?
Client side JavaScript comprises the basic language and predefined objects which are
relevant to running java script in a browser. The client side JavaScript is embedded
directly by in the HTML pages. This script is interpreted by the browser at run time.

Server side JavaScript also resembles like client side java script. It has relevant java
script which is to run in a server. The server side JavaScript are deployed only after
compilation.

22) In which location cookies are stored on the hard disk?


The storage of cookies on the hard disk depends on OS and the browser.

The Netscape navigator on Windows uses cookies.txt file that contains all the cookies.
The path is : c:\Program Files\Netscape\Users\username\cookies.txt

The Internet Explorer stores the cookies on a file username@website.txt. The path is:
c:\Windows\Cookies\username@Website.txt.

23) What is the real name of JavaScript?


The original name was Mocha, a name chosen by Marc Andreessen, founder of
Netscape. In September of 1995, the name was changed to LiveScript. In December
1995, after receiving a trademark license from Sun, the name JavaScript was adopted.
24) What is the difference between undefined value and null
value?
Undefined value: A value that is not defined and has no keyword is known as
undefined value. For example:

1. int number;//Here, number has undefined value.  

Null value: A value that is explicitly specified by the keyword "null" is known as null
value. For example:

1. String str=null;//Here, str has a null value.  

24) How to set the cursor to wait in JavaScript?


The cursor can be set to wait in JavaScript by using the property "cursor". The following
example illustrates the usage:

1. <script>  
2. window.document.body.style.cursor = "wait";   
3. </script>  

25) What is this?


1. var myArray = [[[]]];  

Ans: Three dimensional array.

26) Are Java and JavaScript same?


No, Java and JavaScript are the two different languages. Java is a robust, secured and
object-oriented programming language whereas JavaScript is a client side scripting
language with some limitations.

27) What is negative infinity?


Negative Infinity is a number in JavaScript which can be derived by dividing negative
number by zero.
28) What is difference between View state and Session state?
"View state" is specific to a page in a session whereas "Session state" is specific to a
user or browser that can be accessed across all pages in the web application.

29) What are the pop up boxes available in JavaScript?


o Alert Box

o Confirm Box

o Prompt Box

30) How can we detect OS of the client machine using


JavaScript?
The navigator.appVersion string can be used to detect the operating system on the
client machine.

31) How to submit a form using JavaScript by clicking a link?


Let's see the JavaScript code to submit form on clicking the link.

1. <form name="myform" action="index.php">  
2. Search: <input type='text' name='query' />  
3. <a href="javascript: submitform()">Search</a>  
4. </form>  
5. <script type="text/javascript">  
6. function submitform()  
7. {  
8.   document.myform.submit();  
9. }  
10. </script>  

32) Is JavaScript faster than ASP script?


Yes, because it doesn't require web server's support for execution.
33) How to change the background color of HTML document
using JavaScript?
1. <script type="text/javascript">  
2. document.body.bgColor="pink";  
3. </script>  

34) How to handle exceptions in JavaScript?


By the help of try/catch block, we can handle exceptions in JavaScript. JavaScript
supports try, catch, finally and throw keywords for exception handling.

35) How to validate a form in JavaScript?


Visit here: JavaScript form validation.

36) How to validate email in JavaScript?


Visit here: JavaScript Email validation.

You might also like