0% found this document useful (0 votes)
15K views

4 Scripting Part II

Client-side scripting allows dynamic interactivity on websites by processing scripts in the browser rather than on the server. It handles the user-facing aspects of websites like selecting and manipulating HTML elements. As client-side scripts are processed by the browser rather than the server, they reduce stress on servers and provide faster websites. JavaScript is the most common client-side scripting language and allows websites to have interactive features like clickable buttons and animations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15K views

4 Scripting Part II

Client-side scripting allows dynamic interactivity on websites by processing scripts in the browser rather than on the server. It handles the user-facing aspects of websites like selecting and manipulating HTML elements. As client-side scripts are processed by the browser rather than the server, they reduce stress on servers and provide faster websites. JavaScript is the most common client-side scripting language and allows websites to have interactive features like clickable buttons and animations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

UNIT-4

Introduction To Client Side Scripting:

THE SERVER VS THE CLIENT

All websites run on three components: the server, the database, and the client. The client is simply the browser a person
is using to view a site, and it’s where client-side technology is unpacked and processed. The server is at a remote location
anywhere in the world—housing data, running a site’s back-end architecture, processing requests, and sending pages to
the browser. The client is anywhere your users are viewing your site: mobile devices, laptops, or desktop
computers. Server-side scripting is executed by a web server; client-side scripting is executed by a browser.

Client-end scripts are embedded in a website’s HTML markup code, which is housed on the server in a language that’s
compatible with, or compiled to communicate with, the browser. The browser temporarily downloads that code, and then,
apart from the server, processes it. If it needs to request additional information in response to user clicks, mouse-overs,
etc. (called “events”), a request is sent back to the server.

Client-side scripting is always evolving—it’s growing simpler, more nimble, and easier to use. As a result, sites are faster,
more efficient, and less work is left up to the server.

HOW DOES CLIENT-SIDE SCRIPTING WORK?


There is overlap between the two technologies as they work in tandem, but there are core differences. Server-side
scripting works in the back end of a site, which the user doesn’t see. It creates scaffolding for the site to access its
database, all the behind-the-scenes mechanics that organize and power a website. Client-side code, however, handles what
the user does see.

 Scripts are embedded within and interact with the HTML of your site, selecting elements of it, and then
manipulating those elements to provide an interactive experience.
 Scripts interact with a cascading style sheet (CSS) file that styles the way the page looks.
 It dictates what work the server-side code is going to have to accomplish (where utility should be built around
these front-end functions), and returns data that’s pulled from the site in a way that’s readable by the browser. For
example: If there’s a form for updating a profile, the back end is built to pull specific data from the database to
populate that form, while front-end scripts populate the form with that information.
 Scripts put less stress on the server because they don’t require processing on the server once they’re
downloaded, just when post-backs are made. “Post-backs” perform specific call-and-answers with the server-side
code, and respond to the user immediately.

Client-end scripts are embedded in a website’s HTML markup code, which is housed on the server in a language that’s
compatible with, or compiled to communicate with, the browser. The browser temporarily downloads that code, and then,
apart from the server, processes it. If it needs to request additional information in response to user clicks, mouse-overs,
etc. (called “events”), a request is sent back to the server.

Client-side scripting is always evolving—it’s growing simpler, more nimble, and easier to use. As a result, sites are faster,
more efficient, and less work is left up to the server.

Introduction to java Script: JavaScript was first known as LiveScript, but Netscape changed its name to
JavaScript, possibly because of the excitement being generated by Java. JavaScript made its first appearance in
Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been embedded
in Netscape, Internet Explorer, and other web browsers.

JavaScript ("JS" for short) is a full-fledged dynamic programming language that, when applied to an HTML document, can
provide dynamic interactivity on websites. It was invented by Brendan Eich, co-founder of the Mozilla project, the Mozilla
Foundation, and the Mozilla Corporation.

 JavaScript is a cross-platform, object-oriented scripting language used to make WebPages interactive


(e.g., having complex animations, clickable buttons, popup menus, etc.).
 There are also more advanced server side versions of JavaScript such as Node.js, which allow you to
add more functionality to a website than simply downloading files (such as real time collaboration
between multiple computers).
 Inside a host environment (for example, a web browser), JavaScript can be connected to the objects of its
environment to provide programmatic control over them.

JavaScript contains a standard library of objects, such as Array, Date, and Math, and a core set of language elements such
as operators, control structures, and statements. Core JavaScript can be extended for a variety of purposes by supplementing
it with additional objects
JavaScript Vs Java

JavaScript Java
Object-oriented. No distinction between types of Class-based. Objects are divided into classes and
objects. Inheritance is through the prototype instances with all inheritance through the class
mechanism, and properties and methods can be hierarchy. Classes and instances cannot have
added to any object dynamically. properties or methods added dynamically.

Variable data types are not declared (dynamic Variable data types must be declared (static typing,
typing, loosely typed). strongly typed).

Cannot automatically write to hard disk. Can automatically write to hard disk.

 JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997.

 ECMAScript is the official name of the language.

 From 2015 ECMAScript is named by year (ECMAScript 2015).

ECMAScript Editions
Ver Official Name Description
1 ECMAScript 1 (1997) First Edition.
2 ECMAScript 2 (1998) Editorial changes only.
3 ECMAScript 3 (1999)Added Regular Expressions.Added try/catch.
4 ECMAScript 4 Never released.
5 ECMAScript 5 (2009)Added "strict mode".
Added JSON support.
Added String.trim().
Added Array.isArray().
Added Array Iteration Methods.
5.1 ECMAScript 5.1 (2011) Editorial changes.
6 ECMAScript 2015 Added let and const.
Added default parameter values.
Added Array.find().
Added Array.findIndex().
7 ECMAScript 2016 Added exponential operator (**).
Added Array.prototype.includes.
8 ECMAScript 2017 Added string padding.
Added new Object properties.
Added Async functions.
Added Shared Memory.
9 ECMAScript 2018 Added rest / spread properties.
Added Asynchronous iteration.
Added Promise.finally().
Additions to RegExp.
ECMAScript is often abbreviated to ES.

Browser Support
ECMAScript 3 is fully supported in all browsers.
ECMAScript 5 is fully supported in all modern browsers.

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-anddrop components and sliders
to give a Rich Interface to your site visitors.

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.

JavaScript Data Types

In JavaScript there are 5 different data types that can contain values:

 string
 number
 boolean
 object
 function

There are 6 types of objects:

 Object
 Date
 Array
 String
 Number
 Boolean

And 2 data types that cannot contain values:

 null
 undefined

JavaScript variables can hold many data types: numbers, strings, objects and more:

var length = 16; // Number


var lastName = "Johnson"; // String
var x = {firstName:"John", lastName:"Doe"}; // Object

The Concept of Data Types

In programming, data types is an important concept. To be able to operate on variables, it is important to know
something about the type. Without data types, a computer cannot safely solve this:

var x = 16 + "Volvo";

Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript</h2>
<p>When adding a number and a string, JavaScript will treat the number as a string.</p>
<p id="demo"></p>
<script>
var x = 16 + "Volvo";
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>

Output

JavaScript

When adding a number and a string, JavaScript will treat the number as a string.

16Volvo

Note: When adding a number and a string, JavaScript will treat the number as a string.

JavaScript evaluates expressions from left to right. Different sequences can produce different results:

JavaScript:
var x = 16 + 4 + "Volvo";

Result:

20Volvo

JavaScript:
var x = "Volvo" + 16 + 4;

Result:

Volvo164
In the first example, JavaScript treats 16 and 4 as numbers, until it reaches "Volvo".

In the second example, since the first operand is a string, all operands are treated as strings.

JavaScript Types are Dynamic

JavaScript has dynamic types. This means that the same variable can be used to hold different data types:

Example
var x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String

JavaScript Strings

A string (or a text string) is a series of characters like "John Doe". Strings are written with quotes. You can use
single or double quotes:

Example
var carName1 = "Volvo XC60"; // Using double quotes
var carName2 = 'Volvo XC60'; // Using single quotes

Example

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Strings</h2>

<p>You can use quotes inside a string, as long as they don't match the quotes surrounding the string:</p>

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

<script>
var answer1 = "It's alright";
var answer2 = "He is called 'Johnny'";
var answer3 = 'He is called "Johnny"';

document.getElementById("demo").innerHTML =
answer1 + "<br>" +
answer2 + "<br>" +
answer3;
</script>

</body>
</html>

Output

JavaScript Strings

You can use quotes inside a string, as long as they don't match the quotes surrounding the
string:

It's alright
He is called 'Johnny'
He is called "Johnny"

JavaScript Numbers
JavaScript has only one type of numbers. Numbers can be written with, or without decimals:

Example
var x1 = 34.00; // Written with decimals
var x2 = 34; // Written without decimals

Try it yourself »

Extra large or extra small numbers can be written with scientific (exponential) notation:

Example
var y = 123e5; // 12300000
var z = 123e-5; // 0.00123

JavaScript Booleans : Booleans can only have two values: true or false.

Example
var x = 5;
var y = 5;
var z = 6;
(x == y) // Returns true
(x == z) // Returns false

JavaScript Arrays
JavaScript arrays are written with square brackets. Array items are separated by commas.

The following code declares (creates) an array called cars, containing three items (car names):

Example
var cars = ["Saab", "Volvo", "BMW"];

JavaScript Objects
JavaScript objects are written with curly braces {}. Object properties are written as name:value pairs, separated
by commas.

Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

The object (person) in the example above has 4 properties: firstName, lastName, age, and eyeColor.

The typeof Operator


You can use the JavaScript typeof operator to find the type of a JavaScript variable. The typeof operator returns
the type of a variable or an expression:

Example
typeof "" // Returns "string"
typeof "John" // Returns "string"
typeof "John Doe" // Returns "string"

Undefined
In JavaScript, a variable without a value, has the value undefined. The type is also undefined.

Example
var car; // Value is undefined, type is undefined

Any variable can be emptied, by setting the value to undefined. The type will also be undefined.

Example
car = undefined; // Value is undefined, type is undefined
Empty Values An empty value has nothing to do with undefined. An empty string has
both a legal value and a type.

Example
var car = ""; // The value is "", the typeof is "string"

Null
In JavaScript null is "nothing". It is supposed to be something that doesn't exist.

Unfortunately, in JavaScript, the data type of null is an object.

You can consider it a bug in JavaScript that typeof null is an object. It should be null.

You can empty an object by setting it to null:

Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = null; // Now value is null, but type is still an object

You can also empty an object by setting it to undefined:

Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = undefined; // Now both value and type is undefined

Difference Between Undefined and Null


undefined and null are equal in value but different in type:

typeof undefined // undefined


typeof null // object

null === undefined // false


null == undefined // true

Primitive Data
A primitive data value is a single simple data value with no additional properties and methods.

The typeof operator can return one of these primitive types:

 string
 number
 boolean
 undefined

Example
typeof "John" // Returns "string"
typeof 3.14 // Returns "number"
typeof true // Returns "boolean"
typeof false // Returns "boolean"
typeof x // Returns "undefined" (if x has no value)

Complex Data
The typeof operator can return one of two complex types:

 function
 object

The typeof operator returns "object" for objects, arrays, and null.

The typeof operator does not return "object" for functions.

Example
typeof {name:'John', age:34} // Returns "object"
typeof [1,2,3,4] // Returns "object" (not "array", see note below)
typeof null // Returns "object"
typeof function myFunc(){} // Returns "function"

The typeof operator returns "object" for arrays because in JavaScript arrays are objects.

JavaScript Variables :JavaScript variables are containers for storing data values.
In this example, x, y, and z, are variables:

Example
var x = 5;
var y = 6;
var z = x + y;

JavaScript Identifiers
All JavaScript variables must be identified with unique names. These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

The general rules for constructing names for variables (unique identifiers) are:

 Names can contain letters, digits, underscores, and dollar signs.


 Names must begin with a letter
 Names can also begin with $ and _ (but we will not use it in this tutorial)
 Names are case sensitive (y and Y are different variables)
 Reserved words (like JavaScript keywords) cannot be used as names

JavaScript identifiers are case-sensitive.

JavaScript Operators
The assignment operator (=) assigns a value to a variable.

Assignment
var x = 10;

JavaScript Assignment Operators


Assignment operators assign values to JavaScript variables.

Operator Example Same As


= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y
The addition assignment operator (+=) adds a value to a variable.

Assignment
var x = 10;
x += 5;

JavaScript String Operators

The + operator can also be used to add (concatenate) strings.

Example
var txt1 = "John";
var txt2 = "Doe";
var txt3 = txt1 + " " + txt2;

The result of txt3 will be:

John Doe

Adding Strings and Numbers Adding two numbers, will return the sum, but adding
a number and a string will return a string:

Example
var x = 5 + 5;
var y = "5" + 5;
var z = "Hello" + 5;

The result of x, y, and z will be:

10
55
Hello5

JavaScript Comparison Operators

Operator Description
== equal to
=== equal value and equal type
!= not equal
!= = not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
?: ternary operator

JavaScript Logical Operators

Operator Description
&& logical and
|| logical or
! logical not

JavaScript Type Operators

Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an instance of an object type

JavaScript Bitwise Operators ; Bit operators work on 32 bits numbers.

Any numeric operand in the operation is converted into a 32 bit number. The result is converted
back to a JavaScript number.
Operator Description Example Same as Result Decimal
& AND 5&1 0101 & 0001 0001 1
| OR 5|1 0101 | 0001 0101 5
~ NOT ~5 ~0101 1010 10
^ XOR 5^1 0101 ^ 0001 0100 4
<< Zero fill left shift 5 << 1 0101 << 1 1010 10
>> Signed right shift 5 >> 1 0101 >> 1 0010 2
>>> Zero fill right shift 5 >>> 1 0101 >>> 1 0010 2

Conditional Statements
Very often when you write code, you want to perform different actions for different
decisions.

You can use conditional statements in your code to do this.

In JavaScript we have the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is true


 Use else to specify a block of code to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

For loop , while loop and do-while loop is same as in C language


All conditional statement and loop are same as in C language.
JavaScript Type Conversion

JavaScript variables can be converted to a new variable and another data type:

 By the use of a JavaScript function


 Automatically by JavaScript itself

Converting Numbers to Strings

The global method String() can convert numbers to strings.

It can be used on any type of numbers, literals, variables, or expressions:

Example
String(x) // returns a string from a number variable x
String(123) // returns a string from a number literal 123
String(100 + 23) // returns a string from a number from an expression

Automatic Type Conversion


When JavaScript tries to operate on a "wrong" data type, it will try to convert the value to a
"right" type.

The result is not always what you expect:

5 + null // returns 5 because null is converted to 0


"5" + null // returns "5null" because null is converted to "null"
"5" + 2 // returns "52" because 2 is converted to "2"
"5" - 2 // returns 3 because "5" is converted to 5
"5" * "2" // returns 10 because "5" and "2" are converted to 5 and 2

Converting Strings to Numbers


The global method Number() can convert strings to numbers.

Strings containing numbers (like "3.14") convert to numbers (like 3.14).

Empty strings convert to 0.

Anything else converts to NaN (Not a Number).

Number("3.14") // returns 3.14


Number(" ") // returns 0
Number("") // returns 0
Number("99 88") // returns NaN
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
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?";
}

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

JavaScript Events : HTML events are "things" that happen to HTML elements. When
JavaScript is used in HTML pages, JavaScript can "react" on these events.

HTML Events : An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:

 An HTML web page has finished loading


 An HTML input field was changed
 An HTML button was clicked

Often, when events happen, you may want to do something. JavaScript lets you execute code when events are
detected.

HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

With single quotes:

<element event='some JavaScript'>

With double quotes:

<element event="some JavaScript">

In the following example, an onclick attribute (with code), is added to a <button> element:
Example
<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button>

In the example above, the JavaScript code changes the content of the element with id="demo". In the next example,
the code changes the content of its own element (using this.innerHTML):

Example
<button onclick="this.innerHTML = Date()">The time is?</button>

JAVA SCRIPT ARRAY: An array is a special variable, which can hold more than one value
at a time.

If you have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:

var car1 = "Saab";


var car2 = "Volvo";
var car3 = "BMW";

Using an array literal is the easiest way to create a JavaScript Array.

Syntax:

var array_name = [item1, item2, ...];


Example
var cars = ["Saab", "Volvo", "BMW"];

creating an array program :


1.
1. <!DOCTYPE html>
2. <html>
3. <body>
4.
5. <h2>JavaScript Arrays</h2>
6.
7. <p id="demo"></p>
8.
9. <script>
10. var cars = ["Saab", "Volvo", "BMW"];
11. document.getElementById("demo").innerHTML = cars;
12. </script>
13.
14. </body>
15. </html>

2.
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>

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

<script>
var cars = new Array("Saab", "Volvo", "BMW"); /// using Array constructor.
document.getElementById("demo").innerHTML = cars; //cars[0]—gives info about the element of array
</script> in this case it will return saab.

</body>
</html>

Arrays are Objects

Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. But,
JavaScript arrays are best described as arrays.

Arrays use numbers to access its "elements". In this example, person[0] returns John:

Array:
var person = ["John", "Doe", 46];

Objects use names to access its "members". In this example, person.firstName returns John:

Object:
var person = {firstName:"John", lastName:"Doe", age:46};

program
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p>JavaScript uses names to access object properties.</p>
<p id="demo"></p>
<script>
var person = {firstName:"John", lastName:"Doe", age:46};
document.getElementById("demo").innerHTML = person["firstName"];
</script>
</body>
</html>
Array Elements Can Be Objects

JavaScript variables can be objects. Arrays are special kinds of objects.

Because of this, you can have variables of different types in the same Array.

You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:

myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;

looping Elements
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>

<p>The best way to loop through an array is using a standard for loop:</p>

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

<script>
var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;

text = "<ul>";
for (i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

The Difference Between Arrays and Objects

In JavaScript, arrays use numbered indexes.

In JavaScript, objects use named indexes.

Arrays are a special kind of objects, with numbered indexes.

When to Use Arrays. When to use Objects.

 JavaScript does not support associative arrays.


 You should use objects when you want the element names to be strings (text).
 You should use arrays when you want the element names to be numbers.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>

<p>The typeof operator, when used on an array, returns object:</p>

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

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = typeof fruits;
</script>

</body>
</html>

Output : object
The length Property

The length property of an array returns the length of an array (the number of array elements).

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // the length of fruits is 4

Accessing the Last Array Element


Example
fruits = ["Banana", "Orange", "Apple", "Mango"];
var last = fruits[fruits.length - 1];

Adding Array Elements

The easiest way to add a new element to an array is using the push() method:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); // adds a new element (Lemon) to fruits

Converting Arrays to Strings


The JavaScript method toString() converts an array to a string of (comma separated) array
values.

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();

Result:

Banana,Orange,Apple,Mango
The join() method also joins all array elements into a string.

It behaves just like toString(), but in addition you can specify the separator:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");

Result:

Banana * Orange * Apple * Mango

Popping

The pop() method removes the last element from an array:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop(); // Removes the last element ("Mango") from fruits

The pop() method returns the value that was "popped out":

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.pop(); // the value of x is "Mango"

Pushing
The push() method adds a new element to an array (at the end):

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi"); // Adds a new element ("Kiwi") to fruits

The push() method returns the new array length:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.push("Kiwi"); // the value of x is 5
Shifting Elements
Shifting is equivalent to popping, working on the first element instead of the last.

The shift() method removes the first array element and "shifts" all other elements to a
lower index.

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift(); // Removes the first element "Banana" from fruits

The shift() method returns the string that was "shifted out":

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.shift(); // the value of x is "Banana"

the unshift() method adds a new element to an array (at the beginning), and "unshifts"
older elements:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon"); // Adds a new element "Lemon" to fruits

Splicing an Array
The splice() method can be used to add new items to an array:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");

The first parameter (2) defines the position where new elements should be added (spliced
in).

The second parameter (0) defines how many elements should be removed.

The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.

The splice() method returns an array with the deleted items:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 2, "Lemon", "Kiwi");

<html>
<body>

<h2>JavaScript Array Methods</h2>

<h2>splice()</h2>

<p>The splice() method adds new elements to an array.</p>

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

<p id="demo1"></p>
<p id="demo2"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = "Original Array:<br>" + fruits;
function myFunction() {
fruits.splice(2, 0, "Lemon", "Kiwi");
document.getElementById("demo2").innerHTML = "New Array:<br>" + fruits;
}
</script>

</body>
</html>

Example-2

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array Methods</h2>

<h2>splice()</h2>

<p>The splice() method adds new elements to an array, and returns an array with the deleted elements (if
any).</p>

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

<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = "Original Array:<br> " + fruits;

function myFunction() {
var removed = fruits.splice(2, 2, "Lemon", "Kiwi");
document.getElementById("demo2").innerHTML = "New Array:<br>" + fruits;
document.getElementById("demo3").innerHTML = "Removed Items:<br> " + removed;
}
</script>

</body>
</html>
Using splice() to Remove Elements
With clever parameter setting, you can use splice() to remove elements without leaving
"holes" in the array:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1); // Removes the first element of fruits

The first parameter (0) defines the position where new elements should be added (spliced
in).

The second parameter (1) defines how many elements should be removed.

The rest of the parameters are omitted. No new elements will be added.

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Array Methods</h2>

<h2>splice()</h2>

<p>The splice() methods can be used to remove array elements.</p>


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

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

<script>

var fruits = ["Banana", "Orange", "Apple", "Mango"];

document.getElementById("demo").innerHTML = fruits;

function myFunction() {

fruits.splice(0, 1);

document.getElementById("demo").innerHTML = fruits;

</script>

</body>

</html>

Merging (Concatenating) Arrays

The concat() method creates a new array by merging (concatenating) existing arrays:

Example (Merging Two Arrays)


var myGirls = ["Cecilie", "Lone"];
var myBoys = ["Emil", "Tobias", "Linus"];
var myChildren = myGirls.concat(myBoys); // Concatenates (joins) myGirls and myBoys

The concat() method does not change the existing arrays. It always returns a new array.

The concat() method can take any number of array arguments:

Example (Merging Three Arrays)


var arr1 = ["Cecilie", "Lone"];
var arr2 = ["Emil", "Tobias", "Linus"];
var arr3 = ["Robin", "Morgan"];
var myChildren = arr1.concat(arr2, arr3); // Concatenates arr1 with arr2 and arr3

Slicing an Array
The slice() method slices out a piece of an array into a new array.

This example slices out a part of an array starting from array element 1 ("Orange"):

Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1,3);

The slice() method creates a new array. It does not remove any elements from the source array.

This example slices out a part of an array starting from array element 3 ("Apple"):

Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1,3);

The slice() method can take two arguments like slice(1, 3).

The method then selects elements from the start argument, and up to (but not including) the end argument.

Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(-3, -1);

start Optional. An integer that specifies where to start the selection (The
first element has an index of 0). Use negative numbers to select from
the end of an array. If omitted, it acts like "0"

end Optional. An integer that specifies where to end the selection. If


omitted, all elements from the start position and to the end of the
array will be selected. Use negative numbers to select from the end
of an array
Q.1 How to empty an array in JavaScript?
var arrayList = ['a', 'b', 'c', 'd', 'e', 'f'];

Q.2 How would you check if a number is an integer

Q.3 what is the difference between = = and = = = operator.

JavaScript Strings

A JavaScript string stores a series of characters like "John Doe". A string can be any text inside double or single
quotes:

var carName1 = "Volvo XC60";


var carName2 = 'Volvo XC60';

Example
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Strings</h2>

<p>Strings are written inside quotes. You can use single or double quotes:</p>

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

<script>
var carName1 = "Volvo XC60"; // Double quotes
var carName2 = 'Volvo XC60'; // Single quotes

document.getElementById("demo").innerHTML =
carName1 + " " + carName2;
</script>

</body>
</html>

String indexes are zero-based: The first character is in position 0, the second in 1, and so
on.

String Properties

Property Description
 constructor Returns the string's constructor function
 length Returns the length of a string
 prototype Allows you to add properties and methods to an object

String Methods
Method Description
 charAt() Returns the character at the specified index (position)
 charCodeAt() Returns the Unicode of the character at the specified index
 concat() Joins two or more strings, and returns a new joined strings
 endsWith() Checks whether a string ends with specified string/characters
 fromCharCode() Converts Unicode values to characters
 includes() Checks whether a string contains the specified string/characters
 indexOf() Returns the position of the first found occurrence of a specified value in a string
 lastIndexOf() Returns the position of the last found occurrence of a specified value in a string
 localeCompare() Compares two strings in the current locale

Creating Date Objects

Date objects are created with the new Date() constructor.

There are 4 ways to create a new date object:

new Date()
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(milliseconds)
new Date(date string)

new Date()
new Date() creates a new date object with the current date and time:

Example
var d = new Date();

ex:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript new Date()</h2>


<p>Using new Date(), creates a new date object with the current date and time:</p>

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

<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>

</body>
</html>

Fri Apr 24 2020 13:01:24 GMT+0530 (India Standard Time)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript new Date()</h2>

<p>6 numbers specify year, month, day, hour, minute and second:</p>

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

<script>
var d = new Date(2018, 11, 24, 10, 33, 30);
document.getElementById("demo").innerHTML = d;
</script>

</body>
</html>

JavaScript new Date()

6 numbers specify year, month, day, hour, minute and second:

Mon Dec 24 2018 10:33:30 GMT+0530 (India Standard Time)

Gettime function

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript getTime()</h2>

<p>The internal clock in JavaScript counts from midnight January 1, 1970.</p>


<p>The getTime() function returns the number of milliseconds since then:</p>

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

<script>
var d = new Date();
var months=[“january”,”feb”,march,april,may,june…]
document.getElementById("demo").innerHTML = d.getTime();
document.getElementById("demo").innerHTML = d.getFullYear();
document.getElementById("demo").innerHTML = d.getMonth()+1;
document.getElementById("demo").innerHTML = months[d.getMonth()];

</script>

</body>
</html>

1587713793112
Get full year

var d = new Date();


document.getElementById("demo").innerHTML = d.getFullYear();

2020

Set date method


<!DOCTYPE html>
<html>
<body>

<h2>JavaScript setFullYear()</h2>
<p>The setFullYear() method sets the year of a date object:</p>

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

<script>
var d = new Date();
d.setFullYear(2020);
document.getElementById("demo").innerHTML = d;
</script>

</body>
</html>

d.setFullYear(2011,10,3);

comparing dates:

var today, someday, text;


today = new Date();
someday = new Date();
someday.setFullYear(2100, 0, 14);

if (someday > today) {


text = "Today is before January 14, 2100.";
} else {
text = "Today is after January 14, 2100.";
}
document.getElementById("demo").innerHTML = text;

JavaScript Function: JavaScript functions are defined with the function keyword.
Ex:
function functionName(parameters) {
// code to be executed
}

Function Parameters and Arguments


function functionName(parameter1, parameter2, parameter3) {
// code to be executed
}

Function parameters are the names listed in the function definition. Function arguments are the
real values passed to (and received by) the function.

Parameter Rules

 JavaScript function definitions do not specify data types for parameters.

 JavaScript functions do not perform type checking on the passed arguments.

 JavaScript functions do not check the number of arguments received.

Parameter Defaults

 If a function is called with missing arguments (less than declared), the missing values are set
to: undefined

 Sometimes this is acceptable, but sometimes it is better to assign a default value to the parameter:

Ex: function myFunction(x, y) {


if (y === undefined) {
y = 0;
}
}
Var x= myfunc(77);
Var text= “the value is ”+ x+ “ok”

Function myfunc(arg1, arg2)


{this .firstname=arg1;

This.lastname=arg2;

Var x=new myfunc(“xyz”,”vasu”);

x.firstname;

x.lastname;
The Arguments Object

 JavaScript functions have a built-in object called the arguments object.

 The argument object contains an array of the arguments used when the function was called (invoked).

 This way you can simply use a function to find (for instance) the highest value in a list of numbers:

Example
x = findMax(1, 123, 500, 115, 44, 88);

function findMax() {
var i;
var max = -Infinity;
for (i = 0; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}

EX:

x = sumAll(1, 123, 500, 115, 44, 88);

function sumAll() {
var i;
var sum = 0;
for (i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}

The this Keyword

In JavaScript, the thing called this, is the object that "owns" the current code. The value of this, when used in a
function, is the object that "owns" the function.

Note that this is not a variable. It is a keyword. You cannot change the value of this.

JavaScript Form Validation


HTML form validation can be done by JavaScript.

If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the form from being
submitted:

JavaScript Example
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}

The function can be called when the form is submitted:

HTML Form Example


<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
Automatic HTML Form Validation

HTML form validation can be performed automatically by the browser:

If a form field (fname) is empty, the required attribute prevents this form from being submitted:

HTML Form Example


<form action="/action_page.php" method="post">
<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>

Example

<!DOCTYPE html>
<html>
<body>

<form action="/action_page.php" method="post">


<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>
<p>If you click submit, without filling out the text field,
your browser will display an error message.</p>

</body>
</html>
Output

Data Validation

Data validation is the process of ensuring that user input is clean, correct, and useful.

Typical validation tasks are:

 has the user filled in all required fields?


 has the user entered a valid date?
 has the user entered text in a numeric field?

Most often, the purpose of data validation is to ensure correct user input.

Validation can be defined by many different methods, and deployed in many different ways.

Server side validation is performed by a web server, after input has been sent to the server.

Client side validation is performed by a web browser, before input is sent to a web server.

With the HTML DOM, JavaScript can access and change all the elements of an HTML
document.

The HTML DOM (Document Object Model)

When a web page is loaded, the browser creates a Document Object Model of the page.

The HTML DOM model is constructed as a tree of Objects:

The HTML DOM Tree of Objects


With the object model, JavaScript gets all the power it needs to create dynamic HTML:

 JavaScript can change all the HTML elements in the page


 JavaScript can change all the HTML attributes in the page
 JavaScript can change all the CSS styles in the page
 JavaScript can remove existing HTML elements and attributes
 JavaScript can add new HTML elements and attributes
 JavaScript can react to all existing HTML events in the page

JavaScript can create new HTML events inWhat is the DOM?

The DOM is a W3C (World Wide Web Consortium) standard.

The DOM defines a standard for accessing documents:

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

The W3C DOM standard is separated into 3 different parts:

 Core DOM - standard model for all document types


 XML DOM - standard model for XML documents
 HTML DOM - standard model for HTML documents

What is the HTML DOM?

The HTML DOM is a standard object model and programming interface for HTML. It defines:

 The HTML elements as objects


 The properties of all HTML elements
 The methods to access all HTML elements
 The events for all HTML elements

The HTML DOM is a standard for how to get, change, add, or delete HTML elements.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript can Change HTML</h2>

<p id="p1">Hello World!</p>

<script>
document.getElementById("p1").innerHTML = "New text!";
</script>

<p>The paragraph above was changed by a script.</p>

</body>
</html>

In the example above, getElementById is a method, while innerHTML is a property

Output
JavaScript can Change HTML

New text!

The paragraph above was changed by a script.

The getElementById Method


The most common way to access an HTML element is to use the id of the element.

In the example above the getElementById method used id="p1" to find the element.

The innerHTML Property


The easiest way to get the content of an element is by using the innerHTML property.
The innerHTML property is useful for getting or replacing the content of HTML elements.

The innerHTML property can be used to get or change any HTML element,
including <html> and <body>.

The HTML DOM document object is the owner of all other objects in your web page.

The HTML DOM Document Object

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

document.getElementById(id) Find an element by element id

document.getElementsByTagName(name) Find elements by tag name

document.getElementsByClassName(name) Find elements by class name

Changing HTML Elements


Property Description

element.innerHTML = new html content Change the inner HTML of an element

element.attribute = new value Change the attribute value of an HTML


element
element.style.property = new style Change the style of an HTML element

Method Description

element.setAttribute(attribute, value) Change the attribute value of an HTML


element

<script type = "text/javascript">


<!--
// Form validation code will come here.
function validate() {

if( document.myForm.Name.value == "" ) {


alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" ) {
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" || isNaN(
document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 ) {

alert( "Please provide a zip in the format #####." );


document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" ) {
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>

You might also like