0% found this document useful (0 votes)
38 views44 pages

Client-Side Scripting Server-Side Scripting

javascript

Uploaded by

Aryan Raj
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)
38 views44 pages

Client-Side Scripting Server-Side Scripting

javascript

Uploaded by

Aryan Raj
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
You are on page 1/ 44

Client-side scripting

Web browsers execute client-side scripting. It is used when browsers have all
code. Source code is used to transfer from webserver to user’s computer over
the internet and run directly on browsers. It is also used for validations and
functionality for user events.
It allows for more interactivity. It usually performs several actions without going to
the user. It cannot be basically used to connect to databases on a web server.
These scripts cannot access the file system that resides in the web browser. Pages
are altered on basis of the user’s choice. It can also be used to create “cookies”
that store data on the user’s computer.
Server-side scripting

Web servers are used to execute server-side scripting. They are basically used to
create dynamic pages. It can also access the file system residing at the webserver.
A server-side environment that runs on a scripting language is a web server.
Scripts can be written in any of a number of server-side scripting languages
available. It is used to retrieve and generate content for dynamic pages. It is used
to require to download plugins. In this load times are generally faster than client-
side scripting. When you need to store and retrieve information a database will be
used to contain data. It can use huge resources of the server. It reduces client-side
computation overhead. The server sends pages to the request of the user/client.
Difference between client-side scripting and server-side scripting :
Client-side scripting Server-side scripting

Source code is not visible to the user because its


output
of server-sideside is an HTML page.
Source code is visible to the user.

Its primary function is to manipulate and provide


Its main function is to provide the access to the respective database as per the
requested output to the end user. request.

In this any server-side technology can be used


and it does not
It usually depends on the browser and depend on the client.
its version.

It runs on the user’s computer. It runs on the webserver.

There are many advantages linked The primary advantage is its ability to highly
with this like faster. customize, response
response times, a more interactive requirements, access rights based on user.
Client-side scripting Server-side scripting

application.

It does not provide security for data. It provides more security for data.

It is a technique used in web It is a technique that uses scripts on the


development in which scripts run on webserver to produce a response that is
the client’s browser. customized for each client’s request.

HTML, CSS, and javascript are used. PHP, Python, Java, Ruby are used.

No need of interaction with the


server. It is all about interacting with the servers.

It reduces load on processing unit of


the server. It surge the processing load on the server.

What is Java Script?


JavaScript (js) is a light-weight object-oriented programming language which is used by
several websites for scripting the webpages. It is an interpreted, full-fledged programming
language that enables dynamic interactivity on websites when applied to an HTML
document. It was introduced in the year 1995 for adding programs to the webpages in the
Netscape Navigator browser. Since then, it has been adopted by all other graphical web
browsers. With JavaScript, users can build modern web applications to interact directly
without reloading the page every time. The traditional website uses js to provide several
forms of interactivity and simplicity.

Although, JavaScript has no connectivity with Java programming language. The name was
suggested and provided in the times when Java was gaining popularity in the market. In
addition to web browsers, databases such as CouchDB and MongoDB uses JavaScript as their
scripting and query 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.

History of JavaScript
In 1993, Mosaic, the first popular web browser, came into existence. In the year
1994, Netscape was founded by Marc Andreessen. He realized that the web needed to
become more dynamic. Thus, a 'glue language' was believed to be provided to HTML to
make web designing easy for designers and part-time programmers. Consequently, in 1995,
the company recruited Brendan Eich intending to implement and embed Scheme
programming language to the browser. But, before Brendan could start, the company
merged with Sun Microsystems for adding Java into its Navigator so that it could compete
with Microsoft over the web technologies and platforms. Now, two languages were there:
Java and the scripting language. Further, Netscape decided to give a similar name to the
scripting language as Java's. It led to 'Javascript'. Finally, in May 1995, Marc Andreessen
coined the first code of Javascript named 'Mocha'. Later, the marketing team replaced the
name with 'LiveScript'. But, due to trademark reasons and certain other reasons, in
December 1995, the language was finally renamed to 'JavaScript'. From then, JavaScript
came into existence.

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.

JavaScript Example
1. <script>
2. document.write("Hello JavaScript by JavaScript");
3. </script>

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>

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.

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.

<script type="text/javascript">
alert("Hello WD");
</script>

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.

<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello WD");
}
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</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 WD in an alert dialog box.
message.js

function msg(){
alert("Hello WD");
}

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

index.html

<html>
<head>
<script type="text/javascript" src="message.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>

Advantages of External JavaScript

There will be following benefits if a user creates an external javascript:

1. It helps in the reusability of code in more than one HTML file.


2. It allows easy code readability.
3. It is time-efficient as web browsers cache the external js files, which further reduces
the page loading time.
4. It enables both web designers and coders to work with html and js files parallelly and
separately, i.e., without facing any code conflictions.
5. The length of the code reduces as only we need to specify the location of the js file.

Disadvantages of External JavaScript


There are the following disadvantages of external files:

1. The stealer may download the coder's code using the url of the js file.
2. If two js files are dependent on one another, then a failure in one file may affect the
execution of the other dependent file.
3. The web browser needs to make an additional http request to get the js code.
4. A tiny to a large change in the js code may cause unexpected results in all its
dependent files.
5. We need to check each file that depends on the commonly created external
javascript file.
6. If it is a few lines of code, then better to implement the internal javascript code.

JavaScript Variable
1. JavaScript Local variable
2. 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

var x = 10;
var _value="sonoo";

Incorrect JavaScript variables

var 123=30;
var *aa=320;

Example of JavaScript variable


Let’s see a simple example of JavaScript variable. x

<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>

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:

<script>
function abc(){
var x=10;//local variable
}
</script>
Or,
<script>
If(10<13){
var y=20;//JavaScript local variable
}
</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:

<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</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.

<script>
var value=50;//global variable
function a(){
alert(value);
}
function b(){
alert(value);
}
</script>

Declaring JavaScript global variable within function


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

window.value=90;

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

function m(){
window.value=100;//declaring global variable by window object
}
function n(){
alert(window.value);//accessing global variable from other function
}

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:

var value=50;
function a(){
alert(window.value);//accessing global variable }
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For
example:

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

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

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.


Control Statements in JS/JavaScript If-else and
Switch
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.

if(expression){
//content to be evaluated
}

Flowchart of JavaScript If statement


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

<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>

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

<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>

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.

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.

<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
1. document.write("a is not equal to 10, 15 or 20");
2. }
3. </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.

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.

<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";
}
document.write(result);
</script>

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.

<script>
var grade='B';
var result;
switch(grade){
case 'A':
result+=" A Grade";
case 'B':
result+=" B Grade";
case 'C':
result+=" C Grade";
default:
result+=" No Grade";
}
document.write(result);
</script>

Looping Statements in JS/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
}

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

<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>

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.

while (condition)
{
code to be executed
}

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

<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>

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.

<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>

Output:

21
22
23
24
25
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.

function functionName([arg1, arg2, ...argN]){


//code to be executed
}

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.

<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>

JavaScript Function Arguments


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

<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>

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.

<script>
function getInfo(){
return "hello javatpoint! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>

Output of the above example


hello javatpoint! How r u?

JavaScript Function Object


In JavaScript, the purpose of Function constructor is to create a new Function object. It
executes the code globally. However, if we call the constructor directly, a function is created
dynamically but in an unsecured way.

Syntax
new Function ([arg1[, arg2[, ....argn]],] functionBody)

Parameter
arg1, arg2, .... , argn - It represents the argument used by function.

functionBody - It represents the function definition.


JavaScript Function Methods
Let's see function methods with description.

Method Description

apply() It is used to call a function contains this value and a single array of arguments.

bind() It is used to create a new function.

call() It is used to call a function contains this value and an argument list.

toString() It returns the result in a form of a string.

JavaScript Function Object Examples


Example 1

Let's see an example to display the sum of given numbers.

<script>
var add=new Function("num1","num2","return num1+num2");
document.writeln(add(2,5));
</script>

Output:

Example 2

Let's see an example to display the power of provided value.

<script>
var pow=new Function("num1","num2","return Math.pow(num1,num2)");
document.writeln(pow(2,3));
</script>

Output:
8

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>

Output of the above example


102 Shyam Kumar 40000
2) By creating instance of Object
The syntax of creating object directly is given below:

var objectname=new Object();

Here, new keyword is used to create object.

Let’s see the example of creating object directly.

<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

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.

<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);


</script>
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.

<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;

this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
}
}
e=new emp(103,"Sonoo Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
e.changeSalary(45000);
document.write("<br>"+e.id+" "+e.name+" "+e.salary);
</script>

Output of the above example


103 Sonoo Jaiswal 30000
103 Sonoo Jaiswal 45000

JavaScript Object Methods


The various methods of Object are as follows:

S.No Methods Description


1 Object.assign() This method is used to copy enumerable and own
properties from a source object to a target object

2 Object.create() This method is used to create a new object with the


specified prototype object and properties.

3 Object.defineProperty() This method is used to describe some behavioral


attributes of the property.

4 Object.defineProperties() This method is used to create or configure multiple


object properties.

5 Object.entries() This method returns an array with arrays of the key,


value pairs.

6 Object.freeze() This method prevents existing properties from being


removed.

7 Object.getOwnPropertyDescriptor() This method returns a property descriptor for the


specified property of the specified object.

8 Object.getOwnPropertyDescriptors() This method returns all own property descriptors of a


given object.

9 Object.getOwnPropertyNames() This method returns an array of all properties


(enumerable or not) found.

10 Object.getOwnPropertySymbols() This method returns an array of all own symbol key


properties.

11 Object.getPrototypeOf() This method returns the prototype of the specified


object.

12 Object.is() This method determines whether two values are the


same value.
13 Object.isExtensible() This method determines if an object is extensible

14 Object.isFrozen() This method determines if an object was frozen.

15 Object.isSealed() This method determines if an object is sealed.

16 Object.keys() This method returns an array of a given object's own


property names.

17 Object.preventExtensions() This method is used to prevent any extensions of an


object.

18 Object.seal() This method prevents new properties from being added


and marks all existing properties as non-configurable.

19 Object.setPrototypeOf() This method sets the prototype of a specified object to


another object.

20 Object.values() This method returns an array of values.

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:

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.

<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>

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:

var arrayname=new Array();

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

Let's see the example of creating array directly.

<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";

for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>

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.

<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>

Output of the above example

Jai
Vijay
Smith

JavaScript Array Methods


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

Methods Description

concat() It returns a new array object that contains two or more merged arrays.

copywithin() It copies the part of the given array with its own elements and returns the
modified array.

entries() It creates an iterator object and a loop that iterates over each key/value pair.

every() It determines whether all the elements of an array are satisfying the provided
function conditions.

flat() It creates a new array carrying sub-array elements concatenated recursively till
the specified depth.

flatMap() It maps all array elements via mapping function, then flattens the result into a
new array.

fill() It fills elements into an array with static values.

from() It creates a new array carrying the exact copy of another array element.

filter() It returns the new array containing the elements that pass the provided
function conditions.

find() It returns the value of the first element in the given array that satisfies the
specified condition.

findIndex() It returns the index value of the first element in the given array that satisfies the
specified condition.

forEach() It invokes the provided function once for each element of an array.

includes() It checks whether the given array contains the specified element.

indexOf() It searches the specified element in the given array and returns the index of the
first match.

isArray() It tests if the passed value ia an array.

join() It joins the elements of an array as a string.

keys() It creates an iterator object that contains only the keys of the array, then loops
through these keys.

lastIndexOf() It searches the specified element in the given array and returns the index of the
last match.
map() It calls the specified function for every array element and returns the new array

of() It creates a new array from a variable number of arguments, holding any type
of argument.

pop() It removes and returns the last element of an array.

push() It adds one or more elements to the end of an array.

reverse() It reverses the elements of given array.

reduce(function, It executes a provided function for each value from left to right and reduces the
initial) array to a single value.

reduceRight() It executes a provided function for each value from right to left and reduces the
array to a single value.

some() It determines if any element of the array passes the test of the implemented
function.

shift() It removes and returns the first element of an array.

slice() It returns a new array containing the copy of the part of the given array.

sort() It returns the element of the given array in a sorted order.

splice() It add/remove elements to/from the given array.

toLocaleString() It returns a string containing all the elements of a specified array.

toString() It converts the elements of a specified array into string form, without affecting
the original array.

unshift() It adds one or more elements in the beginning of the given array.
values() It creates a new iterator object carrying values for each index in the array.

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 to authenticate user.

JavaScript provides 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 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=document.myform.name.value;
var password=document.myform.password.value;

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

JavaScript Retype Password Validation


<script type="text/javascript">
function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;

if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;
}
}
</script>

<form name="f1" action="register.jsp" onsubmit="return matchpass()">


Password:<input type="password" name="password" /><br/>
Re-enter Password:<input type="password" name="password2"/><br/>
<input type="submit">
</form>

JavaScript Number Validation


Let's validate the textfield for numeric value only. Here, we are using isNaN() function.
<script>
function validate(){
var num=document.myform.num.value;
if (isNaN(num)){
document.getElementById("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 validation with image


Let’s see an interactive JavaScript form validation example that displays correct and incorrect
image if input is correct or incorrect.

<script>
function validate(){
var name=document.f1.name.value;
var password=document.f1.password.value;
var status=false;

if(name.length<1){
document.getElementById("nameloc").innerHTML=
" <img src='unchecked.gif'/> Please enter your name";
status=false;
}else{
document.getElementById("nameloc").innerHTML=" <img src='checked.gif'/>";
status=true;
}
if(password.length<6){
document.getElementById("passwordloc").innerHTML=
" <img src='unchecked.gif'/> Password must be at least 6 char long";
status=false;
}else{
document.getElementById("passwordloc").innerHTML=" <img src='checked.gif'/>";
}
return status;
}
</script>

<form name="f1" action="#" onsubmit="return validate()">


<table>
<tr><td>Enter Name:</td><td><input type="text" name="name"/>
<span id="nameloc"></span></td></tr>
<tr><td>Enter Password:</td><td><input type="password" name="password"/>
<span id="passwordloc"></span></td></tr>
<tr><td colspan="2"><input type="submit" value="register"/></td></tr>
</table>
</form>

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.

<script>
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
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>

JavaScript Events
The change in the state of an object is known as an Event. In html, there are various events
which represents that some activity is performed by the user or by the browser.
When javascript code is included in HTML, js react over these events and allow the execution.
This process of reacting over the events is called Event Handling. Thus, js handles the HTML
events via Event Handlers.

For example, when a user clicks over the browser, add js code, which will execute the task to
be performed on the event.

Some of the HTML events and their event handlers are:

Mouse events:

Event Performed Event Handler Description

Click onclick When mouse click on an element

Mouseover onmouseover When the cursor of the mouse comes over the element

Mouseout onmouseout When the cursor of the mouse leaves an element


mousedown onmousedown When the mouse button is pressed over the element

Mouseup onmouseup When the mouse button is released over the element

mousemove onmousemove When the mouse movement takes place.

Keyboard events:

Event Performed Event Handler Description

Keydown & Keyup onkeydown & onkeyup When the user press and then release the key

Form events:

Event Performed Event Handler Description

Focus onfocus When the user focuses on an element

Submit onsubmit When the user submits the form

Blur onblur When the focus is away from a form element

Change onchange When the user modifies or changes the value of a form element

Window/Document events

Event Event Description


Performed Handler

Load onload When the browser finishes the loading of the page

Unload onunload When the visitor leaves the current webpage, the browser unloads
it
Resize onresize When the visitor resizes the window of the browser

Let's discuss some examples over events and their handlers.

Click Event

<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function clickevent()
{
document.write("This is JavaTpoint");
}
//-->
</script>
<form>
<input type="button" onclick="clickevent()" value="Who's this?"/>
</form>
</body>
</html>

MouseOver Event

<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert("This is JavaTpoint");
}
//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>

Focus Event

<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
<!--
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}
//-->
</script>
</body>
</html>

Keydown Event

<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
//-->
</script>
</body>
</html>
Load event

<html>
<head>Javascript Events</head>
</br>
<body onload="window.alert('Page successfully loaded');">
<script>
<!--
document.write("The page is loaded successfully");
//-->
</script>
</body>
</html>

JavaScript 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
window.alert("sometext");

The window.alert() method can be written without the window prefix.

Example
alert("I am an alert box!");
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
window.confirm("sometext");

The window.confirm() method can be written without the window prefix.

Example
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}

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
window.prompt("sometext","defaultText");

The window.prompt() method can be written without the window prefix.

Example
let person = prompt("Please enter your name", "Harry Potter");
let text;
if (person == null || person == "") {
text = "User cancelled the prompt.";
} else {
text = "Hello " + person + "! How are you today?";
}

Line Breaks
To display line breaks inside a popup box, use a back-slash followed by the
character n.

Example
alert("Hello\nHow are you?");

You might also like