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

JS_BASICS_LOOP_FN_OBJECT

Uploaded by

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

JS_BASICS_LOOP_FN_OBJECT

Uploaded by

grojamani
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

1

What is JavaScript?

JavaScript is a very powerful client-side scripting language. JavaScript is used


mainly for enhancing the interaction of a user with the webpage. In other words,
you can make your webpage more lively and interactive, with the help of
JavaScript. JavaScript is also being used widely in game development
and Mobile application development.

Javascript History

JavaScript was developed by Brendan Eich in 1995, which appeared in Netscape, a


popular browser of that time.

The language was initially called LiveScript and was later renamed JavaScript.
There are many programmers who think that JavaScript and Java are the same. In
2

fact, JavaScript and Java are very much unrelated. Java is a very complex
programming language whereas JavaScript is only a scripting language.

Features of JavaScript
There are following features of JavaScript:

1. All popular web browsers support JavaScript as they provide built-in execution
environments.

2. JavaScript follows the syntax and structure of the C programming language.


Thus, it is a structured programming language.

3. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).

4. JavaScript is an object-oriented programming language that uses prototypes


rather than using classes for inheritance.

5. It is a light-weighted and interpreted language.

6. It is a case-sensitive language.

7. JavaScript is supportable in several operating systems including, Windows,


macOS, etc.

8. It provides good control to the users over the web browsers.


9. It is a Scripting Language and has nothing to do with Java. Initially, It
was named Mocha, then changed to LiveScript and finally it was
named as JavaScript.

10. JavaScript is an object-based programming language that


supports polymorphism, encapsulation, and inheritance as well.

11. You can run JavaScript not only in the browser but also on
the server and any device which has a JavaScript Engine.

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.
3

3. JavaScript is used to create beautiful web pages and applications. It


is mostly used to make your web look alive and adds variety to the
page.

4. It is also used in smartwatches. An example of this is the popular


smartwatch maker called Pebble that has created a small JavaScript
Framework called Pebble.js.

5. JavaScript is also used to make Games. A lot of developers are


building small-scale games and apps using JavaScript.

Most popular websites like Google, Facebook, Netflix, Amazon, etc make use of
JavaScript to build their websites.

HTML vs CSS vs JavaScript


If you are familiar with JavaScript, you would know the relationship between
HTML, CSS and JavaScript. Let’s have a look at an example to understand the
analogy.
4

HTML(HyperText Markup Language) is more like the skeleton of the web. It


is used for displaying the web.

On the other hand, CSS is like our clothes. It makes the web look better. It
uses CSS which stands for Cascading Style Sheets for styling purpose.

Finally, JavaScript is used to add life to a web page. Just like how kids move
around using the skateboard, the web also motions with the help of
JavaScript.

How to Run JavaScript?

The main advantage of JavaScript is that all modern web browsers


support JavaScript. So, you do not have to worry about whether your site visitor
uses Internet Explorer, Google Chrome, Firefox or any other browser. JavaScript
will be supported. Also, JavaScript runs on any operating system including
Windows, Linux or Mac.

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

o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box,
confirm dialog box and prompt dialog box),
o Displaying clocks etc.
5

<html>

<head>

<title>My First JavaScript code!!!</title>

<script type="text/javascript">

alert("Hello World!");

</script>

</head>

<body>

</body>

</html>

Advantages of JavaScript
The merits of using JavaScript are −

 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.
o JavaScript is used to create beautiful web
pages and applications. It is mostly used to make your web
look alive and adds variety to the page.
6

 It is also used in smartwatches. An example of this is the popular


smartwatch maker called Pebble that has created a small JavaScript
Framework called Pebble.js.

 JavaScript is also used to make Games. A lot of developers are


building small-scale games and apps using JavaScript.

Most popular websites like Google, Facebook, Netflix, Amazon, etc make use of
JavaScript to build their websites.

Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the
following important features −

 Client-side JavaScript does not allow the reading or writing of files. This
has been kept for security reason.
 JavaScript cannot be used for networking applications because there is no
such support available.
 JavaScript doesn't have any multithreading or multiprocessor capabilities.

Once again, JavaScript is a lightweight, interpreted programming language that


allows you to build interactivity into otherwise static HTML pages.

Difference between JAVA and JAVASCRIPT


7

Java Java Script


Java is an Object Oriented Programming Java Script is the object oriented scripting
Language language
It is developed by Sun Microsystems It is developed by Netscape
It is capable of running on multiple operating Java Script code is embedded in HTML and
systems with the help of interpreter runs directly on the browser
The Java compiler converts the code into Java Script code is not compiled they are
byte code. directly run on the browser.
We can make stand-alone application with It is used for providing interactivity to the
the help of Java simple HTML pages
Java uses its own native code then executes it Java script code runs on the java script
on a virtual machine i.e. JVM. enabled browsers. The java script code is
interpreted by the java script engine.

Differences between HTML and DHTML:


 HTML is a mark-up language, while DHTML is a collection of
technology.
 DHTML creates dynamic web pages, whereas HTML creates static web
pages.
 DHTML allows including small animations and dynamic menus in Web
pages.
 DHML used events, methods, properties to insulate dynamism in HTML
Pages.
 DHML is basically using JavaScript and style sheets in an HTML page.
 HTML sites will be slow upon client-side technologies, while DHTML
sites will be fast enough upon client-side technologies.
 HTML creates a plain page without any styles and Scripts called as
HTML. Whereas, DHTML creates a page with HTML, CSS, DOM and
Scripts called as DHTML.
 HTML cannot have any server side code but DHTML may contain server
side code.
 In HTML, there is no need for database connectivity, but DHTML
may require connecting to a database as it interacts with user.
8

 HTML files are stored with .htm or .html extension, while DHTML
files are stored with .dhtm extension.

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
Undefined represents undefined value
Null represents null i.e. no value at all

JavaScript non-primitive data types

The non-primitive data types are as follows:

Data Type Description


Object represents instance through which we can access members
Array represents group of similar values
9

RegExp represents regular expression

JavaScript Example

Compiler ; https://www.javatpoint.com/oprweb/test.jsp?filename=hellojs

1. <h2>Welcome to JavaScript</h2>
2. <script>
3. document.write("Hello JavaScript by JavaScript");
4. </script>

SCRIPTING LANGUAGES: 1) Java script 2. Vb script 3. Php 4.


Python etc.,

JAVASCRIPT OPERATORS
JavaScript operators are symbols that are used to perform operations on operands.
For example:
10

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.

Operator Description Example


+ 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:

Operator Description Example


11

== 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:

Operator Description Example


& 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.

Operator Description Example


&& Logical AND (10==20 && 20==33) = false
|| Logical OR (10==20 || 20==33) = false
! Logical Not !(10==20) = true
12

JavaScript Assignment Operators

The following operators are known as JavaScript assignment operators.

Operator Description Example


= Assign 10+10 = 20
+= Add and assign var a=10; a+=20; Now a = 30
-= Subtract and assign var a=20; a+=10; Now a = 10
*= 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
13

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
14

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;
15

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");
16

11.}
12.else{
13.document.write("a is not equal to 10, 15 or 20");
14.}
15.</script>
Output of the above example
a is equal to 20

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 thanif..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':
17

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>
Test it Now
Output of the above example
B Grade B Grade C Grade No Grade

JavaScript Loops
18

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
19

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 least once 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.


20

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
21

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
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>
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>
22

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);
23

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;
24

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
25

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();


26

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 explicitely.

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
27

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
28

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 explicitely.

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>
29

Test it Now
Output of the above example
Jai
Vijay
Smith

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 1 to 31.
30

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: Thu Oct 08 2015 09:29:13 GMT+0530 (India Standard
Time)

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:
31

Current Time: 9:29:13

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:

JavaScript Math Object


32

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.8255841589998454


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:
33

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);
34

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
35

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.

Browser Object Model

1. Browser Object Model (BOM)

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

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.
37

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.
38

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");
39

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()"/>

Output of the above example

Click

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.


40

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


the root elementthat represents the html document.

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

window.document

Is same as

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
41

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.
42

getElementsByTagName() returns all the elements having the given tag


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

Accessing the field value by document object

In this example, we are going to get the value of input text by user. Here, we are
usingdocument.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>

Output of the above example


Enter Name:

HTML/DOM events for JavaScript


43

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).
onmousedown occurs when mouse button is pressed over an element.
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.

You might also like