0% found this document useful (0 votes)
29 views56 pages

JavaScript Programming Fundamentals Guide

The document provides a comprehensive syllabus for JavaScript, covering its fundamentals, including variables, operators, control flow statements, functions, and objects. It explains how JavaScript enhances web interactivity and details various programming constructs like loops, conditional statements, and popup boxes. Additionally, it introduces the use of timers for delayed code execution and the structure of functions in JavaScript.

Uploaded by

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

JavaScript Programming Fundamentals Guide

The document provides a comprehensive syllabus for JavaScript, covering its fundamentals, including variables, operators, control flow statements, functions, and objects. It explains how JavaScript enhances web interactivity and details various programming constructs like loops, conditional statements, and popup boxes. Additionally, it introduces the use of timers for delayed code execution and the structure of functions in JavaScript.

Uploaded by

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

JavaScript

SYLLABUS: JavaScript: Using JavaScript in an HTML Document, Programming


Fundamentals of JavaScript – Variables, Operators, Control Flow Statements,
Popup Boxes, Functions – Defining and Invoking a Function, Defining Function
arguments, Defining a Return Statement, Calling Functions with Timer, JavaScript
Objects - String, RegExp, Math, Date, Browser Objects - Window, Navigator,
History, Location, Document, Cookies, Document Object Model, Form Validation
using JavaScript

JavaScript is a text-based programming language used both on the client-side and server-
side that allows you to make web pages interactive. Where HTML and CSS are languages
that give structure and style to web pages, JavaScript gives web pages interactive elements
that engage a user. Common examples of JavaScript that you might use every day include
the search box on Amazon
JavaScript is mainly used for web-based applications and web browsers. But JavaScript is
also used beyond the Web in software, servers and embedded hardware controls.
JavaScript can calculate, manipulate and validate data.

Using JavaScript in an HTML Document


Ex.
<html>
<body>
<script type="text/javascript">
[Link]("SYCS”);
</script>
</body>
P<r o/ hgtrma m
l >m i n g Fundamentals of JavaScript – Variables, Operators, Control Flow
Statements, Popup Boxes

JavaScript variables are containers for storing data values.


In this example, x, y, and z, are variables, declared with the var keyword:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Variables</h2>
<p id="demo"></p>

<script>
var x = 5;
var y = 6;
var z = x + y;

"The value of z is: " + z;


</script>
Ja<v/baS
odcryi>pt Operators
J a<v/ ha tSmc rl >ip t 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

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) 10%3=1
++ 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


== 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==20) = false
| Bitwise OR (10==20 | 20==33) = false
^ Bitwise XOR (10==20 ^ 20==33) = false
~ Bitwise NOT (~10) = -10
<< Bitwise Left (10<<2) = 40
Shift
>> Bitwise Right (10>>2) = 2
Shift

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
JavaScript Assignment Operators
The following operators are known as JavaScript assignment operators.
Operator Description Example
= Assign 10+10 = 20
+= Add and assign a=a+20
a+=20
var a=10; a+=20; Now a = 30
-= Subtract and assign a=a-20
var a=20; a-=10; Now a = 10
*= Multiply and assign a=a*20
var a=10; a*=20; Now a = 200
/= Divide and assign a=a/5
var a=10; a/=2; Now a = 5
%= Modulus and assign var a=10; a%=2; Now a = 0

Control Flow Statements

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 the expression is true. The signature of JavaScript if
statement is given below.
if(expression)
{
//content to be evaluated
}
Flowchart of JavaScript If statement

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


<html>
<body>
<script>
var a=20;
if(a>10){
[Link]("value of a is greater than 10");
}
</script>
</body>
</html>

JavaScript If...else Statement


It evaluates the content whether condition is true of false. The syntax of JavaScript
if-else statement is given below.
if(expression)
{
//content to be evaluated if condition is true
}
else
{
//content to be evaluated if condition is false
}
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.
<html>
<body>
<script>
var a=20;
if(a%2==0){
[Link]("a is even number");
}
else{
[Link]("a is odd number");
}
</script>
</body>
</html>

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.

if(expression1)
{
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else
{
//content to be evaluated if no expression is true
}
Let’s see the simple example of if else if statement in javascript.
<html>
<body>
<script>
var a=20;
if(a==10){
[Link]("a is equal to 10");
}
else if(a==15){
[Link]("a is equal to 15");
}
else if(a==20){
[Link]("a is equal to 20");
}
else{
[Link]("a is not equal to 10, 15 or 20");
}
</script>
</body>
</html>

JavaScript Switch statement:


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.
switch(expression)
{
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......

default:
code to be executed if above values are not matched;
}
Let’s see the simple example of switch statement in javascript.
<!DOCTYPE html>
<html>
<body>
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
[Link](result);
</script>
</body>
</html>

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.
for (initialization; condition; increment)
{
code to be executed
}

<!DOCTYPE html>
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
[Link](i + "<br/>")
}
</script>
</body>
</html>

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.

while (condition)
{
//code to be executed
}
Let’s see the simple example of while loop in javascript.

<!DOCTYPE html>
<html>
<body>
<script>
var i=11;
while (i<=15)
{
[Link](i + "<br/>");
i++;
}
</script>
</body>
</html>

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.
do{
// code to be executed
}while (condition);
Let’s see the simple example of do while loop in javascript.
<script>
var i=21;
do{
[Link](i + "<br/>");
i++;
}while (i<=25);
</script>

Popup Boxes
JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
Alert Box
An alert box is often used if you want to make sure information comes through to
the user.
When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
[Link]("sometext");
The [Link]() method can be written without the window prefix
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Alert</h2>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
alert("I am an alert box!");
}
</script>

</body>
</html>
Confirm Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to
proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.
Syntax
[Link]("sometext");
The [Link]() method can be written without the window prefix.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Confirm Box</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else { txt = "You pressed Cancel!";
}[Link]("demo").innerHTML = txt;
}</script>
</body>
</html>
Prompt Box
A prompt box is often used if you want the user to input a value before entering a
page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to
proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel"
the box returns null.
Syntax
[Link]("sometext","defaultText");
The [Link]() method can be written without the window prefix.
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Prompt</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
var person = prompt("Please enter your name:", "Harry Potter");
if (person == null || person == "") {
txt = "User cancelled the prompt.";
} else {
txt = "Hello " + person + "! How are you today?";
}
[Link]("demo").innerHTML = txt;
}
</script>
</body>
</html>

Functions
Defining and Invoking a Function, Defining Function arguments, Defining a Return
Statement, Calling Functions with Timer
Defining and Invoking a Function:
JavaScript functions are defined with the function keyword.
functions are declared with the following syntax:
function functionName(parameters)
{
// code to be executed
}
Example
function myFunction(a, b)
{
return a * b;
}
Invoking a JavaScript Function
The code inside a function is not executed when the function is defined.
The code inside a function is executed when the function is invoked(call).
It is common to use the term "call a function" instead of "invoke a function".
It is also common to say "call upon a function", "start a function", or "execute a
function".

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

</head>

<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello">
</form>

</body>
</html>
Defining Function arguments
Function Parameters are the names that are define in the function definition and real
values passed to the function in function definition are known as arguments.
Syntax:
function Name(parameter1, parameter2, paramet3,parameter4)
{
// Statements
}
Parameter Rules:
There is no need to specify the data type for parameters in JavaScript function
definitions.
It does not perform type checking based on passed in JavaScript function.
It does not check the number of received arguments.
Parameters:
Name: It is used to specify the name of the function.
Arguments: It is provided in the argument field of the function.
<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
[Link] (name + " is " + age + " years old.");
}
</script>
</head>

<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello('Zara', 7)" value = "Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the
code after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the
"caller":
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

<p>This example calls a function which performs a calculation, and returns the
result:</p>

<p id="demo"></p>
<script>
function myFunction(p1, p2) {
return p1 * p2;
}
[Link]("demo").innerHTML = myFunction(4, 3);
</script>
</body>
</html>

Calling Functions with Timer


Working with Timers
A timer is a function that enables us to execute a function at a particular time.
Using timers you can delay the execution of code so that it does not get done at the
exact moment an event is triggered or the page is loaded. For example, you can use
timers to change the advertisement banners on your website at regular intervals, or
display a real-time clock, etc. There are two timer functions in JavaScript:
setTimeout() and setInterval().
The following section will show you how to create timers to delay code execution
as well as how to perform one or more actions repeatedly using these functions in
JavaScript.
Executing Code After a Delay
The setTimeout() function is used to execute a function or specified piece of code
just once after a certain period of time. Its basic syntax is setTimeout(function,
milliseconds).
This function accepts two parameters: a function, which is the function to execute,
and an optional delay parameter, which is the number of milliseconds representing
the amount of time to wait before executing the function (1 second = 1000
milliseconds). Let's see how it works:
<!DOCTYPE html>
<html>
<body>

<p>Click the button to wait 3 seconds, then alert "Hello".</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
setTimeout(function(){ alert("Hello"); }, 3000);
}
</script>

</body>
</html>
The clearTimeout() method stops the execution of the function specified in
setTimeout().
[Link](timeoutVariable)
<!DOCTYPE html>
<html>
<body>

<p>Click "Try it". Wait 3 seconds. The page will alert "Hello".</p>
<p>Click "Stop" to prevent the first function to execute.</p>
<p>(You must click "Stop" before the 3 seconds are up.)</p>

<button onclick="myVar = setTimeout(myFunction, 3000)">Try it</button>

<button onclick="clearTimeout(myVar)">Stop it</button>

<script>
function myFunction() {
alert("Hello");
}
</script>
</body>
</html>
The setInterval() Method
The setInterval() method repeats a given function at every given time-interval.
[Link](function, milliseconds);
<!DOCTYPE html>
<html>
<body>

<p>A script on this page starts this clock:</p>

<p id="demo"></p>

<script>
var myVar = setInterval(myTimer, 3000);

function myTimer() {
var d = new Date();
[Link]("demo").innerHTML = [Link]();
}
</script>
</body>
</html>

The clearInterval() method stops the executions of the function specified in the
setInterval() method.
[Link](timerVariable)

JavaScript String
The JavaScript string is an object that represents a sequence of characters.
There are 2 ways to create string in JavaScript
By string literal
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:
var stringname="string value";
Let's see the simple example of creating string literal.
<script>
var str="This is string literal";
[Link](str);
</script>

2) By string object (using new keyword)


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

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.
<script>
var stringname = new String("hello javascript string");
[Link](stringname);
</script>

Methods Description

charAt() It provides the char value present at the specified index.


sycs=0123
1
y
charCodeAt() It provides the Unicode value of a character present at the
specified index.

concat() It provides a combination of two or more strings.

indexOf() It provides the position of a char value present in the given


string.

lastIndexOf() It provides the position of a char value present in the given


string by searching a character from the last position.

search() It searches a specified regular expression in a given string


and returns its position if a match occurs.
match() It searches a specified regular expression in a given string
and returns that regular expression if a match occurs.

replace() It replaces a given string with the specified replacement.

substr() It is used to fetch the part of the given string on the basis
of the specified starting position and length.

substring() It is used to fetch the part of the given string on the basis
of the specified index.

slice() It is used to fetch the part of the given string. It allows us


to assign positive as well negative index.

toLowerCase() It converts the given string into lowercase letter.

toLocaleLowerCase( It converts the given string into lowercase letter on the


) basis of hosts current locale.

toUpperCase() It converts the given string into uppercase letter.

toString() It provides a string representing the particular object.

valueOf() It provides the primitive value of string object.

split() It splits a string into substring array, then returns that newly
created array.

trim() It trims the white space from the left and right side of the
string.

Example1:
<!DOCTYPE html>
<html>
<body>
<script>
var str="javascript";
[Link]([Link](2));
</script>
</body>
</html>

Example 2:
<!DOCTYPE html>
<html>
<body>
<script>
var s1="JavaScript toLowerCase Example";
var s2=[Link]();
[Link](s2);
</script>
</body>
</html>
Regular expression
A regular expression is an object that describes a pattern of characters.
The JavaScript RegExp class represents regular expressions, and both String and
RegExp define methods that use regular expressions to perform powerful pattern-
matching and search-and-replace functions on text.
Syntax
var pattern = new RegExp(pattern, attributes);
or simply
var pattern = /pattern/attributes;
here/mumbai/i is a city

● pattern − A string that specifies the pattern of the regular expression or another
regular expression.
● attributes − An optional string containing any of the "g", "i", and "m"
attributes that specify global, case-insensitive, and multi-line matches,
respectively.
Brackets
Brackets ([ ]) have a special meaning when used in the context of regular
expressions. They are used to find a range of characters.
[Link]. Expression & Description

1 [...]
Any one character between the brackets.
3 [0-9]
It matches any decimal digit from 0 through 9.

4 [a-z]
It matches any character from lowercase a through lowercase z.

5 [A-Z]
It matches any character from uppercase A through uppercase Z.

6 [a-Z]
It matches any character from lowercase a through uppercase Z.

The ranges shown above are general; you could also use the range [0-3] to match
any decimal digit ranging from 0 through 3, or the range [b-v] to match any
lowercase character ranging from b through v.
Quantifiers
The frequency or position of bracketed character sequences and single characters
can be denoted by a special character. Each special character has a specific
connotation. The +, *, ?, and $ flags all follow a character sequence.
[Link]. Expression & Description

1 p+
It matches any string containing one or more p's.

2 p*
It matches any string containing zero or more p's.

3 p?
It matches any string containing at most one p.
4 p{N}
It matches any string containing a sequence of N p's

5 p{2,3}
It matches any string containing a sequence of two or three p's.

6 p{2, }
It matches any string containing a sequence of at least two p's.

7 p$
It matches any string with p at the end of it.

8 ^p
It matches any string with p at the beginning of it.

Examples
Following examples explain more about matching characters.
[Link] Expression & Description
.
1 [^a-z A-Z]
It matches any string not containing any of the characters ranging from a
through z and A through Z.

2 p.p
It matches any string containing p, followed by any character, in turn
followed by another p.

3 ^.{2}$
It matches any string containing exactly two characters.
4 <b>(.*)</b>
It matches any string enclosed within <b> and </b>.

5 p(hp)*
It matches any string containing a p followed by zero or more instances of
the sequence hp.

Literal characters
[Link] Character & Description
.
1 Alphanumeric
Itself- A to Z ,0-9

2 \0
The NUL character (\u0000)

3 \t
Tab (\u0009

4 \n
Newline (\u000A)

5 \v
Vertical tab (\u000B)
6 \f
Form feed (\u000C)

7 \r
Carriage return (\u000D)

8 \xnn
The Latin character specified by the hexadecimal number nn; for example,
\x0A is the same as \n

9 \uxxxx
The Unicode character specified by the hexadecimal number xxxx; for
example, \u0009 is the same as \t

10 \cX
The control character ^X; for example, \cJ is equivalent to the newline
character \n

Metacharacters
A metacharacter is simply an alphabetical character preceded by a backslash that
acts to give the combination a special meaning.
For instance, you can search for a large sum of money using the '\d' metacharacter:
/([\d]+)000/, Here \d will search for any string of numerical character.
The following table lists a set of metacharacters which can be used in PERL Style
Regular Expressions.
[Link] Character & Description
.
1 .
a single character
2 \s
a whitespace character (space, tab, newline)

3 \S
non-whitespace character

4 \d
a digit (0-9)

5 \D
a non-digit

6 \w
a word character (a-z, A-Z, 0-9, _)

7 \W
a non-word character

8 [\b]
a literal backspace (special case).

9 [aeiou]
matches a single character in the given set

10 [^aeiou]
matches a single character outside the given set
11 (foo|bar|baz)
matches any of the alternatives specified

Modifiers
Several modifiers are available that can simplify the way you work with regexps,
like case sensitivity, searching in multiple lines, etc.
[Link] Modifier & Description
.

1 i
Perform case-insensitive matching.

2 m
Specifies that if the string has newline or carriage return characters, the ^
and $ operators will now match against a newline boundary, instead of a
string boundary

3 g
Performs a global match that is, find all matches rather than stopping after
the first match.

RegExp Properties
Here is a list of the properties associated with RegExp and their description.
[Link]. Property & Description

1 constructor
Specifies the function that creates an object's prototype.
2 global
Specifies if the "g" modifier is set.

3 ignoreCase
Specifies if the "i" modifier is set.

4 lastIndex
The index at which to start the next match.

5 multiline
Specifies if the "m" modifier is set.

6 source
The text of the pattern.

In the following sections, we will have a few examples to demonstrate the usage of
RegExp properties.
RegExp Methods
Here is a list of the methods associated with RegExp along with their description.
[Link] Method & Description
.

1 exec()
Executes a search for a match in its string parameter.

2 test()
Tests for a match in its string parameter.
3 toSource()
Returns an object literal representing the specified object; you can use this
value to create a new object.

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

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

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

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

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

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

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

7 cos()
Returns the cosine of a number.

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

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

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

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

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

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

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

16 sin()
Returns the sine of a number.

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

18 tan()
Returns the tangent of a number.

19 toSource()
Returns the string "Math".

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.

JavaScript Date Methods


Let's see the list of JavaScript date methods with their description.
Methods Description

getDate() It returns the integer value between 1 and 31 that represents


the day for the specified date on the basis of local time.

getDay() It returns the integer value between 0 and 6 that represents the
day of the week on the basis of local time.

getFullYears() It returns the integer value that represents the year on the basis
of local time.

getHours() It returns the integer value between 0 and 23 that represents


the hours on the basis of local time.

getMilliseconds() It returns the integer value between 0 and 999 that represents
the milliseconds on the basis of local time.

getMinutes() It returns the integer value between 0 and 59 that represents


the minutes on the basis of local time.

getMonth() It returns the integer value between 0 and 11 that represents


the month on the basis of local time.

getSeconds() It returns the integer value between 0 and 60 that represents


the seconds on the basis of local time.
getUTCDate() It returns the integer value between 1 and 31 that represents
the day for the specified date on the basis of universal time.

getUTCDay() It returns the integer value between 0 and 6 that represents the
day of the week on the basis of universal time.

getUTCFullYears It returns the integer value that represents the year on the basis
() of universal time.

getUTCHours() It returns the integer value between 0 and 23 that represents


the hours on the basis of universal time.

getUTCMinutes() It returns the integer value between 0 and 59 that represents


the minutes on the basis of universal time.

getUTCMonth() It returns the integer value between 0 and 11 that represents


the month on the basis of universal time.

getUTCSeconds() It returns the integer value between 0 and 60 that represents


the seconds on the basis of universal time.

setDate() It sets the day value for the specified date on the basis of local
time.

setDay() It sets the particular day of the week on the basis of local time.

setFullYears() It sets the year value for the specified date on the basis of local
time.

setHours() It sets the hour value for the specified date on the basis of local
time.

setMilliseconds() It sets the millisecond value for the specified date on the basis
of local time.
setMinutes() It sets the minute value for the specified date on the basis of
local time.

setMonth() It sets the month value for the specified date on the basis of
local time.

setSeconds() It sets the second value for the specified date on the basis of
local time.

setUTCDate() It sets the day value for the specified date on the basis of
universal time.

setUTCDay() It sets the particular day of the week on the basis of universal
time.

setUTCFullYears It sets the year value for the specified date on the basis of
() universal time.

setUTCHours() It sets the hour value for the specified date on the basis of
universal time.

setUTCMilliseco It sets the millisecond value for the specified date on the basis
nds() of universal time.

setUTCMinutes() It sets the minute value for the specified date on the basis of
universal time.

setUTCMonth() It sets the month value for the specified date on the basis of
universal time.

setUTCSeconds() It sets the second value for the specified date on the basis of
universal time.

toDateString() It returns the date portion of a Date object.


toISOString() It returns the date in the form ISO format string.

toJSON() It returns a string representing the Date object. It also


serializes the Date object during JSON serialization.

toString() It returns the date in the form of string.

toTimeString() It returns the time portion of a Date object.

toUTCString() It converts the specified date in the form of string using UTC
time zone.

valueOf() It returns the primitive value of a Date object.

Example:
<html>
<body>
Current Date and Time: <span id="txt"></span>
<script>
var today=new Date();

</script>
</body>
</html>
Window Object

Browser Object Model

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:

[Link]("hello javatpoint");

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.
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 a message with ok and
cancel buttons.

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

open() opens the new window.

close() closes the current window.

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

Example of open() in javascript


It displays the content in a new window.

<script type="text/javascript">
function msg()
{
open("[Link]
}
</script>
<input type="button" value="javatpoint" onclick="msg()"/>
JavaScript 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:

[Link]

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.

<html>

<body>

<h2>JavaScript Navigator Object</h2>

<script>

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

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

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

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

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

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

</script>

</body>

</html>

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

[Link]

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.

Location Object

The location object contains information about the current URL.

The location object is part of the window object and is accessed through the
[Link] property.

Location Object Properties

Property Description

Hash Sets or returns the anchor part (#) of a URL


Host Sets or returns the hostname and port number of a URL

hostname Sets or returns the hostname of a URL

Href Sets or returns the entire URL

origin Returns the protocol, hostname and port number of a URL

pathname Sets or returns the path name of a URL

Port Sets or returns the port number of a URL

protocol Sets or returns the protocol of a URL

search Sets or returns the querystring part of a URL

Location Object Methods


Method Description

assign() Loads a new document

reload() Reloads the current document

replace() Replaces the current document with a new one

<!DOCTYPE html>

<html>

<body>

<p id="a"></p>

<script>

= " URL of the currently loaded page is "

+ [Link]; </script>

</body></html>
JavaScript HTML DOM Document

The document object represents your web page.

If you want to access any element in an HTML page, you always start with accessing
the document object.

Below are some examples of how you can use the document object to access and
manipulate HTML.

Finding HTML Elements

Method Description

[Link](id) Find an element by element id

[Link](na Find elements by tag name


me)

[Link](na Find elements by class name


me)

Changing HTML Elements


Property Description

[Link] = new html content Change the inner HTML of an


element

[Link] = new value Change the attribute value of an


HTML element

[Link] = new style Change the style of an HTML


element

Method Description

[Link](attribute, value) Change the attribute value of an


HTML element
Adding and Deleting Elements

Method Description

[Link](element) Create an HTML element

[Link](element) Remove an HTML element

[Link](element) Add an HTML element

[Link](new, old) Replace an HTML element

[Link](text) Write into the HTML output stream

Adding Events Handlers

Method Description
[Link](id).onclick = Adding event handler code to an
function(){code} onclick event

Finding HTML Objects

The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections,
and properties. These are still valid in HTML5.

Later, in HTML DOM Level 3, more objects, collections, and properties were added.

Property Description DOM

[Link] Returns all <a> elements that have a name 1


attribute

[Link] Returns all <applet> elements (Deprecated 1


in HTML5)

[Link] Returns the absolute base URI of the 3


document
[Link] Returns the <body> element 1

[Link] Returns the document's cookie 1

[Link] Returns the document's doctype 3

[Link] Returns the <html> element 3


ment

[Link] Returns the mode used by the browser 3


de

[Link] Returns the URI of the document 3


I

[Link] Returns the domain name of the document 1


server
[Link] Obsolete. Returns the DOM configuration 3

[Link] Returns all <embed> elements 3

[Link] Returns all <form> elements 1

[Link] Returns the <head> element 3

[Link] Returns all <img> elements 1

[Link] Returns the DOM implementation 3


on

[Link] Returns the document's encoding (character 3


set)

[Link] Returns the date and time the document was 3


updated
[Link] Returns all <area> and <a> elements that 1
have a href attribute

[Link] Returns the (loading) status of the document 3

[Link] Returns the URI of the referrer (the linking 1


document)

[Link] Returns all <script> elements 3

[Link] Returns if error checking is enforced 3


ecking

[Link] Returns the <title> element 1


JavaScript Cookies

A cookie is an amount of information that persists between a server-side and a client-


side. A web browser stores this information at the time of browsing.

A cookie contains the information as a string generally in the form of a name-value


pair separated by semi-colons. It maintains the state of a user and remembers the
user's information among all the web pages.

How Cookies Works?

When a user sends a request to the server, then each of that request is treated as a
new request sent by the different user.

So, to recognize the old user, we need to add the cookie with the response from the
server.

browser at the client-side.

Now, whenever a user sends a request to the server, the cookie is added with that
request automatically. Due to the cookie, the server recognizes the users.

JavaScript Cookies
How to create a Cookie in JavaScript?

In JavaScript, we can create, read, update and delete a cookie by using


[Link] property.

The following syntax is used to create a cookie:

[Link]="name=value";

JavaScript Cookie Example

<!DOCTYPE html>

<html>
<head>

</head>
<body>

<input type="button" value="setCookie" onclick="setCookie()">

<input type="button" value="getCookie" onclick="getCookie()">


<script>
function setCookie()

[Link]="username=Duke Martin";

}
function getCookie()

if([Link]!=0)
{

alert([Link]);

}
else

alert("Cookie not available");


}
}

</script>

</body>

</html>

DOM (Document Object Model)


The Document Object Model (DOM) is a programming interface for HTML and
XML(Extensible markup language) documents. It defines the logical structure of
documents and the way a document is accessed and manipulated.
Note: It is called as a Logical structure because DOM doesn’t specify any
relationship between objects.
DOM is a way to represent the webpage in the structured hierarchical way so that it
will become easier for programmers and users to glide through the document. With
DOM, we can easily access and manipulate tags, IDs, classes, Attributes or Elements
using commands or methods provided by Document object.
Structure of DOM:
DOM can be thought of as Tree or Forest(more than one tree). The term structure
model is sometimes used to describe the tree-like representation of a document. One
important property of DOM structure models is structural isomorphism: if any two
DOM implementations are used to create a representation of the same document,
they will create the same structure model, with precisely the same objects and
relationships.

Why called as Object Model ?


Documents are modeled using objects, and the model includes not only the structure
of a document but also the behavior of a document and the objects of which it is
composed of like tag elements with attributes in HTML.
Properties of DOM:
Let’s see the properties of document object that can be accessed and modified by the
document object.
1. Window Object: Window Object is at always at top of hierarchy.

2. Document object: When HTML document is loaded into a window, it

becomes a document object.


3. Form Object: It is represented by form tags.

4. Link Objects: It is represented by link tags.

5. Anchor Objects: It is represented by a href tags.

6. Form Control Elements:: Form can have many control elements such
as text fields, buttons, radio buttons, and checkboxes, etc.

Methods of Document Object

 write(“string”): writes the given string on the document.


 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 givenclass
name.

JavaScript Form Validation

It is important to validate the form submitted by the user because it can have
inappropriate values. So, validation is must to authenticate users.
JavaScript provides a facility to validate the form on the client-side so data
processing will be faster than server-side validation. Most of the web developers
prefer JavaScript form validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers
and more fields.
JavaScript Form Validation Example
In this example, we are going to validate the name and password. The name can’t be
empty and the 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.

<script>
function validateform(){
var name=[Link];
var

if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if([Link]<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="[Link]" onsubmit="return
validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>

JavaScript Number Validation

<script>
function validate(){
var num=[Link];
if (isNaN(num)){
[Link]("numloc").innerHTML="Enter Numeric value only";
return false;
}else{
return true;
}
}
</script>
<form name="myform" onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>

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:

email id must contain the @ and . character


There must be at least one character before and after the @.
There must be at least two characters after . (dot).
Let's see the simple example to validate the email field.

<script>
function validateemail()
{
var x=[Link];
var atposition=[Link]("@");
var dotposition=[Link](".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=[Link]){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n
dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#" onsubmit="return
validateemail();">
Email: <input type="text" name="email"><br/>

<input type="submit" value="register">


</form>

You might also like