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

Unit-2-Javascript Theory

JavaScript is a lightweight, interpreted programming language that allows for adding interactivity to HTML pages. It is commonly used to validate form entries, detect browser capabilities, and dynamically modify HTML content. JavaScript code can be embedded directly in HTML files or linked via external .js files. It is an object-oriented language that is easy to learn and runs on the client-side, allowing for real-time interactions with users.

Uploaded by

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

Unit-2-Javascript Theory

JavaScript is a lightweight, interpreted programming language that allows for adding interactivity to HTML pages. It is commonly used to validate form entries, detect browser capabilities, and dynamically modify HTML content. JavaScript code can be embedded directly in HTML files or linked via external .js files. It is an object-oriented language that is easy to learn and runs on the client-side, allowing for real-time interactions with users.

Uploaded by

Tech Channel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

JavaScript

What is JavaScript?
Javascript sometimes abbreviated as JS is a dynamic computer programming language. It is
lightweight and most commonly used as a part of web pages, whose implementations allow
client-side script to interact with the user and make dynamic pages. It is an interpreted
programming language with object-oriented capabilities. Javascript is dynamically weakly
typed (Type juggling which means we do not have to specify datatype).
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.

Some of the features are:


 JavaScript is a lightweight, interpreted programming language.
 Designed for creating network-centric applications.
 Complementary to and integrated with HTML.
 Open and cross-platform.

Javascript uses the syntax which is influenced by the „C‟ language. Javascript copies many
names and naming conventions from JAVA but the two languages are otherwise unrelated and
have very different semantics.
The main usage of Javascript is to add various functionalities to webform, validation, browser
detection, creation of cookies etc. It is one of the most popular scripting language and is
supported by almost all the web browsers. It was designed to add interactivity to HTML pages
by embedding directly into HTML pages.

Client-Side JavaScript
Client-side JavaScript is the most common form of the language. The script should be included
in or referenced by an HTML document for the code to be interpreted by the browser.
It means that a web page need not be a static HTML, but can include programs that interact with
the user, control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI server-
side scripts. For example, you might use JavaScript to check if the user has entered a valid e-
mail address in a form field.
The JavaScript code is executed when the user submits the form, and only if all the entries are
valid, they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and
other actions that the user initiates explicitly or implicitly.
Difference between Java and JavaScript

JAVA JAVASCRIPT
JavaScript is an object based programming
Java is an object oriented programming language.
language.
Java creates application that can run in a virtual
JavaScript code run on browser only.
machine or browser.
Java code is compiled. JavaScript is interpreted.
Java code allows programmer full functionality JavaScript code contains limited number of
and needs to be compiled. commands and features.
JavaScript was earlier known as LiveScript
The first name of Java was OAK and was
and was developed by Brendan Eich,
developed by James Gosling , Sun MicroSystems.
Netscape.
Java is high-level, static, compiled and strongly JavaScript is text based, dynamic and
type language. weakly typed language.
In JavaScript there is var keyword is used
In Java there is different datatypes like int, float,
to define variable and according to value it
string, etc and you have to specify datatype with
takes datatype of that variable
variable while declaring.
automatically.
Java program has file extension “.Java” and after
compilation it becomes “.class” file that contains
JavaScript file has file extension “.js”.
bytecodes which is executed by JVM : Java
Virtual Machine.
Objects of Java are class based. Objects of JavaScript are prototype based.
JavaScript has function based scope and
Java has block based scope.
object based context.
Java can be used to develop stand-alone JavaScript cannot be used to develop stand-
application. alone application.

Advantages of JavaScript
The merits of using JavaScript are:
 Less server interaction: You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.
 Immediate feedback to the visitors: They don't have to wait for a page reload to see if
they have forgotten to enter something.
 Increased interactivity: You can create interfaces that react when the user hovers over
them with a mouse or activates them via the keyboard.
 Richer interfaces: You can use JavaScript to include such items as drag and drop
components and sliders to give a Rich Interface to your site visitors.
 Easy to learn.
 Platform Independent.
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.
 Limited range of built-in methods: JS is a limited version of java language and it has
very limited range of built-in functions that can be used directly on the webpage.
 JavaScript cannot be used for networking applications because there is no such support
available.
 JavaScript doesn't have any multithreading or multiprocessor capabilities.
 Limited debugging and development tools are available.

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


you to build interactivity into otherwise static HTML pages.

JavaScript Development Tools


 Microsoft FrontPage
 Macromedia Dreamweaver MX
 Macromedia HomeSite 5

Where does JavaScript Fit In?


Remember
1. client opens connection to server
2. client sends request to server
3. server sends response to client
4. client and server close connection
• What about Step 5?
5.Client renders (displays) the response received from server
• Step 5 involves displaying HTML and running any JavaScript code within the HTML

JavaScript Syntax Introduction


1. Whitespace and Line Breaks: JavaScript ignores spaces, tabs, and newlines that appear in
JavaScript programs. You can use spaces, tabs, and newlines freely in your program and you are
free to format and indent your programs in a neat and consistent way that makes the code easy
to read and understand.
2. Semicolons are Optional: if each of your statements are placed on a separate line
Note: It is a good programming practice to use semicolons.
3. Case Sensitivity: JavaScript is a case-sensitive language.
4. Comments in JavaScript:
JavaScript supports both C-style and C++ style comments. Thus:
 Any text between a // and the end of a line is treated as a comment and is ignored by
JavaScript.
 Any text between the characters /* and */ is treated as a comment. This may span
multiple lines.
 JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats
this as a single-line comment, just as it does the // comment.
 The HTML comment closing sequence --> is not recognized by JavaScript so it should
be written as //-->.

JavaScript Where To Use


1. The <script> Tag : In HTML, JavaScript code must be inserted between <script> and
</script> tags.
<html>
<body>

<h2>JavaScript in Body</h2>

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

<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

</body>
</html>

JavaScript Functions and Events: A JavaScript function is a block of JavaScript code, that
can be executed when "called" for.
2. JavaScript in <head>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>

<body>

<h2>JavaScript in Head</h2>

<p id="demo">A Paragraph.</p>

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

</body>
</html>
3. JavaScript in <body>
<html>
<body>

<h2>JavaScript in Body</h2>

<p id="demo">A Paragraph.</p>

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

<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>

</body>
</html>

4. External JavaScript
Scripts can also be placed in external files. External scripts are practical when the same code is
used in many different web pages. JavaScript files have the file extension .js. To use an external
script, put the name of the script file in the src (source) attribute of a <script> tag.
External file: myScript.js
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
<html>
<body>

<h2>External JavaScript</h2>

<p id="demo">A Paragraph.</p>

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

<p>(myFunction is stored in an external file called "myScript.js")</p>

<script src="myScript.js"></script>

</body>
</html>
Some Examples of Javascript
1. JavaScript Can Change HTML Content : One of many JavaScript HTML methods is
getElementById().

<html>
<body>

<h2>What Can JavaScript Do? </h2>

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello


JavaScript!"'>Click Me!</button>

</body>
</html>

Note: JavaScript accepts both double and single quotes.

2. JavaScript Can Change HTML Attributes


<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p>JavaScript can change HTML attributes.</p>

<p>In this case JavaScript changes the src (source) attribute of an image.</p>

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the


light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the


light</button>

</body>
</html>
3. JavaScript Can Change HTML Styles (CSS)
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can change the style of an HTML element.</p>

<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">


Click Me!</button>
</body>
</html>

JavaScript Output Method


JavaScript can "display" data in different ways:

 Writing into an HTML element, using innerHTML.


 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().
 Writing into the browser console, using console.log().

1. <script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

2. <script>
document.write(5 + 6);
</script>

3. <button type="button" onclick="document.write(5 + 6)">Try it</button>

4. <script>
window.alert(5 + 6);
</script>

5. <script>
alert(5 + 6);
</script>

6. <script>
console.log(5 + 6);
</script>

VARIABLES

JavaScript Datatypes
One of the most fundamental characteristics of a programming language is the set of data types
it supports. These are the type of values that can be represented and manipulated in a
programming language. JavaScript allows you to work with three primitive data types:

Numbers, e.g., 123, 120.50 etc.


Strings of text, e.g. "This text string" etc.
Boolean, e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which defines only a
single value. In addition to these primitive data types, JavaScript supports a composite data type
known as object. Java does not make a distinction between integer values and floating point
values. All numbers in JavaScript are represented as floating-point values.
JavaScript Variables
Before you use a variable in a JavaScript program, you must declare it. Variables are declared
with the var keyword as follows. Storing a value in a variable is called variable initialization.

<script type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>

Note: Use the var keyword only for declaration or initialization, once for the life of any
variable name in a document. You should not re-declare same variable twice. JavaScript is
untyped language. This means that a JavaScript variable can hold a value of any data type.

JavaScript Variable Names


While naming your variables in JavaScript, keep the following rules in mind.
 You should not use any of the JavaScript reserved keywords as a variable name. These
keywords are mentioned in the next section. For example, break or boolean variable
names are not valid.
 JavaScript variable names should not start with a numeral (0-9). They must begin with a
letter or an underscore character. For example, 123test is an invalid variable name but
_123test is a valid one.
 JavaScript variable names are case-sensitive. For example, Name and name are two
different variables.

JavaScript Variable Scope


Global Variables: A global variable has global scope which means it can be defined anywhere
in your JavaScript code.
Local Variables: A local variable will be visible only within a function where it is defined.
Function parameters are always local to that function.

<script type="text/javascript">
var myVar = "global"; // Declare a global variable

function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
</script>
JavaScript Reserved Words

abstract else instanceof switch


boolean enum int synchronized
break export interface this
byte extends long throw
case false native throws
catch final new transient
char finally null true
class float package try
const for private typeof
continue function protected var
debugger goto public void
default if return volatile
delete implements short while
do import static with
double in super

OPERATORS
JavaScript supports the following types of operators.
 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Bitwise Operators
 Assignment Operators
 Conditional (or ternary) Operators

1. Arithmetic Operators
<html>
<body>

<script type="text/javascript">

var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";

document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);

document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);

document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);

document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);

document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);

a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);

b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);

</script>

</body>
</html>

2. Comparison Operators
<html>
<body>

<script type="text/javascript">
var a = 10;
var b = 20;
var linebreak = "<br />";

document.write("(a == b) => ");


result = (a == b);
document.write(result);
document.write(linebreak);

document.write("(a < b) => ");


result = (a < b);
document.write(result);
document.write(linebreak);

document.write("(a > b) => ");


result = (a > b);
document.write(result);
document.write(linebreak);

document.write("(a != b) => ");


result = (a != b);
document.write(result);
document.write(linebreak);

document.write("(a >= b) => ");


result = (a >= b);
document.write(result);
document.write(linebreak);

document.write("(a <= b) => ");


result = (a <= b);
document.write(result);
document.write(linebreak);
</script>

</body>
</html>

3. Logical Operators
Assume variable A holds 10 and variable B holds 20, then:
Sr.No Operator and Description
&& (Logical AND)
1 If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.
|| (Logical OR)
2 If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical NOT
3
operator will make it false.
Ex: ! (A && B) is false.
4. Bitwise Operators: JavaScript supports the following bitwise operators −

Assume variable A holds 2 and variable B holds 3, then −

Sr.No Operator and Description


& (Bitwise AND)

1 It performs a Boolean AND operation on each bit of its integer arguments.

Ex: (A & B) is 2.
| (BitWise OR)

2 It performs a Boolean OR operation on each bit of its integer arguments.

Ex: (A | B) is 3.
^ (Bitwise XOR)

It performs a Boolean exclusive OR operation on each bit of its integer arguments.


3
Exclusive OR means that either operand one is true or operand two is true, but not both.

Ex: (A ^ B) is 1.
~ (Bitwise Not)

4 It is a unary operator and operates by reversing all the bits in the operand.

Ex: (~B) is -4.


<< (Left Shift)

It moves all the bits in its first operand to the left by the number of places specified in the
second operand. New bits are filled with zeros. Shifting a value left by one position is
5
equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying by 4,
and so on.

Ex: (A << 1) is 4.
>> (Right Shift)

Binary Right Shift Operator. The left operand‟s value is moved right by the number of
6
bits specified by the right operand.

Ex: (A >> 1) is 1.
>>> (Right shift with Zero)

This operator is just like the >> operator, except that the bits shifted in on the left are
7
always zero.

Ex: (A >>> 1) is 1.
Example:
<html>
<body>

<script type="text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";

document.write("(a & b) => ");


result = (a & b);
document.write(result);
document.write(linebreak);

document.write("(a | b) => ");


result = (a | b);
document.write(result);
document.write(linebreak);

document.write("(a ^ b) => ");


result = (a ^ b);
document.write(result);
document.write(linebreak);

document.write("(~b) => ");


result = (~b);
document.write(result);
document.write(linebreak);

document.write("(a << b) => ");


result = (a << b);
document.write(result);
document.write(linebreak);

document.write("(a >> b) => ");


result = (a >> b);
document.write(result);
document.write(linebreak);
//-->
</script>

</body>
</html>
5. Assignment Operators

Sr.No Operator and Description


= (Simple Assignment )

1 Assigns values from the right side operand to the left side operand

Ex: C = A + B will assign the value of A + B into C


+= (Add and Assignment)

2 It adds the right operand to the left operand and assigns the result to the left operand.

Ex: C += A is equivalent to C = C + A
−= (Subtract and Assignment)

It subtracts the right operand from the left operand and assigns the result to the left
3
operand.

Ex: C -= A is equivalent to C = C - A
*= (Multiply and Assignment)

It multiplies the right operand with the left operand and assigns the result to the left
4
operand.

Ex: C *= A is equivalent to C = C * A
/= (Divide and Assignment)

It divides the left operand with the right operand and assigns the result to the left
5
operand.

Ex: C /= A is equivalent to C = C / A
%= (Modules and Assignment)

6 It takes modulus using two operands and assigns the result to the left operand.

Ex: C %= A is equivalent to C = C % A

6. Miscellaneous Operator
6.1 Conditional Operator (? :)

The conditional operator first evaluates an expression for a true or false value and then executes
one of the two given statements depending upon the result of the evaluation.

Sr.No Operator and Description


? : (Conditional )
1
If Condition is true? Then value X : Otherwise value Y
Example:
<html>
<body>

<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";

document.write ("((a > b) ? 100 : 200) => ");


result = (a > b) ? 100 : 200;
document.write(result);
document.write(linebreak);

document.write ("((a < b) ? 100 : 200) => ");


result = (a < b) ? 100 : 200;
document.write(result);
document.write(linebreak);
//-->
</script>

</body>
</html>

typeof Operator

The typeof operator is a unary operator that is placed before its single operand, which can be of
any type. Its value is a string indicating the data type of the operand.

The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number,
string, or boolean value and returns true or false based on the evaluation.

Here is a list of the return values for the typeof Operator.

Type String Returned by typeof


Number "number"
String "string"
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"
<html>
<body>

<script type="text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";

result = (typeof b == "string" ? "B is String" : "B is Numeric");


document.write("Result => ");
document.write(result);
document.write(linebreak);

result = (typeof a == "string" ? "A is String" : "A is Numeric");


document.write("Result => ");
document.write(result);
document.write(linebreak);
//-->
</script>

<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
JavaScript Selection Statements

1. if...else Statement

JavaScript supports the following forms of if..else statement −

 if statement
 if...else statement
 if...else if... statement.

Example 1:
<html>
<body>

<script type="text/javascript">
<!--
var age = 20;

if( age > 18 ){


document.write("<b>Qualifies for driving</b>");
}
//-->
</script>

</body>
</html>

Example 2:
<html>
<body>

<script type="text/javascript">
<!--
var age = 15;

if( age > 18 ){


document.write("<b>Qualifies for driving</b>");
}

else{
document.write("<b>Does not qualify for driving</b>");
}
//-->
</script>

</body>
</html>

Example 3:
<html>
<body>

<script type="text/javascript">
<!--
var book = "maths";
if( book == "history" ){
document.write("<b>History Book</b>");
}

else if( book == "maths" ){


document.write("<b>Maths Book</b>");
}

else if( book == "economics" ){


document.write("<b>Economics Book</b>");
}

else{
document.write("<b>Unknown Book</b>");
}
//-->
</script>

</body>
<html>

2. Switch case

<html>
<body>

<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
case 'A': document.write("Good job<br />");
break;

case 'B': document.write("Pretty good<br />");


break;

case 'C': document.write("Passed<br />");


break;

case 'D': document.write("Not so good<br />");


break;
case 'F': document.write("Failed<br />");
break;

default: document.write("Unknown grade<br />")


}
document.write("Exiting switch block");
//-->
</script>

</body>
</html>

Break statements play a major role in switch-case statements. Try the following code that
uses switch-case statement without any break statement.

<html>
<body>

<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
case 'A': document.write("Good job<br />");
case 'B': document.write("Pretty good<br />");
case 'C': document.write("Passed<br />");
case 'D': document.write("Not so good<br />");
case 'F': document.write("Failed<br />");
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>

</body>
</html>
LOOPING: JavaScript supports all the necessary loops to ease down the pressure of
programming.

The while Loop

The syntax of while loop in JavaScript is as follows −

while (expression){
Statement(s) to be executed if expression is true
}
Example
<html>
<body>

<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop ");

while (count < 10){


document.write("Current Count : " + count + "<br />");
count++;
}

document.write("Loop stopped!");
//-->
</script>

</body>
</html>

The do...while Loop

The syntax for do-while loop in JavaScript is as follows −

do{
Statement(s) to be executed;
} while (expression);

Note − Don‟t miss the semicolon used at the end of the do...while loop.

Example
<html>
<body>

<script type="text/javascript">
<!--
var count = 0;

document.write("Starting Loop" + "<br />");


do{
document.write("Current Count : " + count + "<br />");
count++;
}

while (count < 5);


document.write ("Loop stopped!");
//-->
</script>

</body>
</html>

For Loop

The 'for' loop is the most compact form of looping. It includes the following three important
parts −

 The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.
 The test statement which will test if a given condition is true or not. If the condition is
true, then the code given inside the loop will be executed, otherwise the control will
come out of the loop.
 The iteration statement where you can increase or decrease your counter.

You can put all the three parts in a single line separated by semicolons.

The syntax of for loop is JavaScript is as follows −

for (initialization; test condition; iteration statement){


Statement(s) to be executed if test condition is true
}
Example
<html>
<body>

<script type="text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");

for(count = 0; count < 10; count++){


document.write("Current Count : " + count );
document.write("<br />");
}

document.write("Loop stopped!");
//-->
</script>

</body>
</html>

JavaScript for...in loop : We‟ll discuss this loop again during discussion of JavaScript Object.

The for...in loop is used to loop through an object's properties. once you understand how
objects behave in JavaScript, you will find this loop very useful.

Syntax
for (variablename in object){
statement or block to execute
}

In each iteration, one property from object is assigned to variablename and this loop continues
till all the properties of the object are exhausted.
Example
<html>
<body>

<script type="text/javascript">
<!--
var aProperty;
document.write("Navigator Object Properties<br /> ");

for (aProperty in navigator) {


document.write(aProperty);
document.write("<br />");
}
document.write ("Exiting from the loop!");
//-->
</script>

<p>Set the variable to different object and then try...</p>


</body>
</html>

JavaScript - Loop Control (Jump Statements)


The break Statement
Example
<html>
<body>

<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");

while (x < 20)


{
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}

document.write("Exiting the loop!<br /> ");


//-->
</script>

</body>
</html>
Output
Entering the loop
2
3
4
5
Exiting the loop!

The continue Statement


Example
<html>
<body>

<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");

while (x < 10)


{
x = x + 1;

if (x == 5){
continue; // skip rest of the loop body
}
document.write( x + "<br />");
}

document.write("Exiting the loop!<br /> ");


//-->
</script>

</body>
</html>

Using Labels to Control the Flow


a label can be used with break and continue to control the flow more precisely. A label is
simply an identifier followed by a colon (:) that is applied to a statement or a block of code.
Note − Line breaks are not allowed between the ‘continue’ or ‘break’ statement and its label
name. Also, there should not be any other statement in between a label name and associated
loop.
Example
<html>
<body>

<script type="text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name

for (var i = 0; i < 5; i++)


{
document.write("Outerloop: " + i + "<br />");
innerloop:
for (var j = 0; j < 5; j++)
{
if (j > 3 ) break ; // Quit the innermost loop
if (i == 2) break innerloop; // Do the same thing
if (i == 4) break outerloop; // Quit the outer loop
document.write("Innerloop: " + j + " <br />");
}
}

document.write("Exiting the loop!<br /> ");


//-->
</script>

</body>
</html>
Output
Entering the loop!
Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 2
Outerloop: 3
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 4
Exiting the loop!
Example
<html>
<body>

<script type="text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name

for (var i = 0; i < 3; i++)


{
document.write("Outerloop: " + i + "<br />");
for (var j = 0; j < 5; j++)
{
if (j == 3){
continue outerloop;
}
document.write("Innerloop: " + j + "<br />");
}
}

document.write("Exiting the loop!<br /> ");


//-->
</script>

</body>
</html>
JavaScript - Functions
A function is a group of reusable code which can be called anywhere in your program. This
eliminates the need of writing the same code again and again. It helps programmers in writing
modular codes. Functions allow a programmer to divide a big program into a number of small
and manageable functions.

Like any other advanced programming language, JavaScript also supports all the features
necessary to write modular code using functions. JavaScript contains built-in functions as well
as allows us to write our own functions as well.

Function Definition

Before we use a function, we need to define it. The most common way to define a function in
JavaScript is by using the function keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded by curly braces.

Syntax

The basic syntax is shown here.

<script type="text/javascript">
<!--
function functionname(parameter-list)
{
statements
}
//-->
</script>
Example
<script type="text/javascript">
<!--
function sayHello()
{
alert("Hello there");
}
//-->
</script>
Calling a Function

To invoke a function somewhere later in the script, you would simply need to write the name of
that function as shown in the following code.

<html>
<head>

<script type="text/javascript">
function sayHello()
{
document.write ("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>
Function Parameters

A function can take multiple parameters separated by comma.

Example
<html>
<head>

<script type="text/javascript">
function sayHello(name, age)
{
document.write (name + " is " + age + " years old.");
}
</script>

</head>
<body>
<p>Click the following button to call the function</p>

<form>
<input type="button" onclick="sayHello('Amit', 7)" value="Say Hello">
</form>

</body>
</html>

The return Statement

A JavaScript function can have an optional return statement. This is required if you want to
return a value from a function. This statement should be the last statement in a function.

For example, you can pass two numbers in a function and then you can expect the function to
return their multiplication in your calling program.

Example
It defines a function that takes two parameters and concatenates them before returning the
resultant in the calling program.
<html>
<head>

<script type="text/javascript">
function concatenate(first, last)
{
var full;
full = first + last;
return full;
}

function secondFunction()
{
var result;
result = concatenate('Amit', 'Arora');
document.write (result );
}
</script>

</head>

<body>
<p>Click the following button to call the function</p>

<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>

</body>
</html>
JavaScript Objects
Objects are composed of attributes. If an attribute contains a function, it is considered to be a
method of the object, otherwise the attribute is considered a property.

Object Properties

Object properties can be any of the three primitive data types, or any of the abstract data types,
such as another object. Object properties are usually variables that are used internally in the
object's methods, but can also be globally visible variables that are used throughout the page.
The syntax for adding a property to an object is:

objectName.objectProperty = propertyValue;

For example: The following code gets the document title using the "title" property of the
document object.

var str = document.title;

Object Methods

Methods are the functions that let the object do something or let something be done to it. There
is a small difference between a function and a method – at a function is a standalone unit of
statements and a method is attached to an object and can be referenced by the this keyword.
For example: Following is a simple example to show how to use the write() method of
document object to write any content on the document.

document.write ("This is test");

User-Defined Objects

The new operator is used to create an instance of an object. To create an object, the new
operator is followed by the constructor method. In the following example, the constructor
methods are Object(), Array(), and Date(). These constructors are built-in JavaScript functions.

var employee = new Object();


var books = new Array("C++", "Perl", "Java");

var day = new Date("August 15, 1947");


The Object ( ) Constructor

Example 1: Following example demonstrates how to create an Object

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
var book = new Object(); // Create the object

book.subject = "Perl"; // Assign properties to the object

book.author = "Mohtashim";
</script>
</head>

<body>
<script type="text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body>

</html>

Example 2: This example demonstrates how to create an object with a User-Defined Function.
Here this keyword is used to refer to the object that has been passed to a function.

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author)
{
this.title = title;
this.author = author;
}
</script>
</head>

<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
</script>
</body>
</html>
Defining Methods for an Object
Example: Following example shows how to add a function along with an object.

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
// Define a function which will work as a method
function addPrice(amount)
{
this.price = amount;
}

function book(title, author)


{
this.title = title;
this.author = author;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>

<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
Built-In JavaScript Objects
Some basic objects are built-in to JavaScript
 Number
 String
 Date
 Array
 Boolean
 Math

Number object
Syntax
The syntax for creating a number object is as follows:
var val = new Number(number);

In the place of number, if you provide any non-number argument, then the argument cannot be converted
into a number, it returns NaN (Not-a-Number).

Number Properties
Sr.No Property & Description
MAX_VALUE
1
The largest possible value a number in JavaScript can have 1.7976931348623157E+308
MIN_VALUE
2
The smallest possible value a number in JavaScript can have 5E-324
NaN
3
Equal to a value that is not a number.
NEGATIVE_INFINITY
4
A value that is less than MIN_VALUE.
POSITIVE_INFINITY
5
A value that is greater than MAX_VALUE

Number Methods
Sr.No Method & Description
toExponential()
1
Forces a number to display in exponential notation, even if the number is in the range in
which JavaScript normally uses standard notation.
toFixed()
2
Formats a number with a specific number of digits to the right of the decimal.
toLocaleString()
3
Returns a string value version of the current number in a format that may vary according
to a browser's local settings.
toPrecision()
4
Defines how many total digits (including digits to the left and right of the decimal) to
display of a number.
toString()
5
Returns the string representation of the number's value.
valueOf()
6
Returns the number's value.

Example 1:

<body>

<script>

var val = Number.MAX_VALUE;


document.write ("Value of Number.MAX_VALUE : " + val +"<br/>");

var val = Number.MIN_VALUE;


document.write("Value of Number.MIN_VALUE : " + val +"<br/>");

var dayOfMonth = 50;


if (dayOfMonth < 1 || dayOfMonth > 31)
{
dayOfMonth = Number.NaN
alert("Day of Month must be between 1 and 31.")
}
Document.write("Value of dayOfMonth : " + dayOfMonth );

</script>

</body>

Example 2:
<html>
<head>
<title>Javascript Method toExponential()</title>
</head>
<body>
<script type="text/javascript">

var num=77.1234;
var val = num.toExponential();
document.write("num.toExponential() is : " + val );
document.write("<br />");

val = num.toExponential(4);
document.write("num.toExponential(4) is : " + val );
document.write("<br />");

val = 77.1234.toExponential();
document.write("77.1234.toExponential()is : " + val );
document.write("<br />");

val = 77.0.toExponential(3);
document.write("77.toExponential(3)is : " + val );
document.write("<br />");

var num=177.1234;
document.write("num.toFixed(6) is : " + num.toFixed(6));
document.write("<br />");

document.write("(1.23e+20).toFixed(2) is:" +
(1.23e+20).toFixed(2));

document.write("<br />");
document.write("(1.23e-10).toFixed(2) is : " +
(1.23e-10).toFixed(2));

document.write("<br />");
var num = new Number(177.12345435);
document.write( num.toLocaleString());

document.write("num.toPrecision(2) is " + num.toPrecision(2));


document.write("<br />");

var num = new Number(15);


document.write("num.toString() is " + num.toString());
document.write("<br />");
document.write("num.toString(2) is " + num.toString(2));
document.write("<br />");
document.write("num.toString(4) is " + num.toString(4));
document.write("<br />");

</script>
</body>
</html>

Output:
num.toExponential() is : 7.71234e+1
num.toExponential(4) is : 7.7123e+1
77.1234.toExponential()is : 7.71234e+1
77.toExponential(3)is : 7.700e+1
num.toFixed(6) is : 177.123400
(1.23e+20).toFixed(2) is:123000000000000000000.00
(1.23e-10).toFixed(2) is : 0.00
177.123num.toPrecision(2) is 1.8e+2
num.toString() is 15
num.toString(2) is 1111
num.toString(4) is 33

Converting Variables to Numbers

There are 3 JavaScript methods that can be used to convert variables to numbers:

 The Number() method


 The parseInt() method
 The parseFloat() method

These methods are not number methods, but global JavaScript methods.

Global Methods

JavaScript global methods can be used on all JavaScript data types.

These are the most relevant methods, when working with numbers:

Method Description
Number() Returns a number, converted from its argument.
parseFloat() Parses its argument and returns a floating point number
parseInt() Parses its argument and returns an integer

Example of number()
Number(true); // returns 1
Number(false); // returns 0
Number("10"); // returns 10
Number(" 10"); // returns 10
Number("10 "); // returns 10
Number("10 20"); // returns NaN
Number("John"); // returns NaN
Number(new Date("2017-09-30")); // returns 1506729600000 (on a date object)
Example of parseInt()

parseInt("10"); // returns 10
parseInt("10.33"); // returns 10
parseInt("10 20 30"); // returns 10
parseInt("10 years"); // returns 10
parseInt("years 10"); // returns NaN

Example of parseFloat()
parseFloat("10"); // returns 10
parseFloat("10.33"); // returns 10.33
parseFloat("10 20 30"); // returns 10
parseFloat("10 years"); // returns 10
parseFloat("years 10"); // returns NaN

String object
As JavaScript automatically converts between string primitives and String objects, you can call any of
the helper methods of the String object on a string primitive.
Syntax
Use the following syntax to create a String object:
var val = new String(string);
The string parameter is a series of characters that has been properly encoded.

String Properties
Sr.No Property & Description
constructor
1
Returns a reference to the String function that created the object.
length
2
Returns the length of the string.
prototype
3
The prototype property allows you to add properties and methods to an object.

String Methods
Sr.No Method & Description
charAt()
1
Returns the character at the specified index.
concat()
2
Combines the text of two strings and returns a new string.
indexOf()
3
Returns the index within the calling String object of the first occurrence of the specified
value, or -1 if not found.
4 lastIndexOf()
Returns the index within the calling String object of the last occurrence of the specified
value, or -1 if not found.
localeCompare()
5
Returns a number indicating whether a reference string comes before or after or is the
same as the given string in sort order.
replace()
6
Used to find a match between a regular expression and a string, and to replace the
matched substring with a new substring.
search()
7
Executes the search for a match between a regular expression and a specified string.
slice()
8
Extracts a section of a string and returns a new string.
split()
9
Splits a String object into an array of strings by separating the string into substrings.
substr()
10
Returns the characters in a string beginning at the specified location through the
specified number of characters.
substring()
11
Returns the characters in a string between two indexes into the string.
toLowerCase()
12
Returns the calling string value converted to lower case.
toString()
13
Returns a string representing the specified object.
toUpperCase()
14
Returns the calling string value converted to uppercase.
valueOf()
15
Returns the primitive value of the specified object.
big()
16
Creates a string to be displayed in a big font as if it were in a <big> tag.
blink()
17
Creates a string to blink as if it were in a <blink> tag
18 bold()
Creates a string to be displayed as bold as if it were in a <b> tag
italics()
19
Causes a string to be italic, as if it were in an <i> tag.
small()
20
Causes a string to be displayed in a small font, as if it were in a <small> tag.
strike()
21
Causes a string to be displayed as struck-out text, as if it were in a <strike> tag.
sub()
22
Causes a string to be displayed as a subscript, as if it were in a <sub> tag
sup()
23
Causes a string to be displayed as a superscript, as if it were in a <sup> tag

String Length

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


OR
var txt = new String("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
var sln = txt.length;

Finding a String in a String


var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");

var str = "Please locate where 'locate' occurs!";


var pos = str.lastIndexOf("locate");

Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found.

Both methods accept a second parameter as the starting position for the search:

Example
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate",15);

Searching for a String in a String

var str = "Please locate where 'locate' occurs!";


var pos = str.search("locate");

Note: The two methods, indexOf() and search(), are equal? They accept the same arguments
(parameters), and return the same value?
The two methods are NOT equal. These are the differences:

 The search() method cannot take a second start position argument.


 The indexOf() method cannot take powerful search values (regular expressions).

Extracting String Parts

There are 3 methods for extracting a part of a string:

 slice(start, end)
 substring(start, end)
 substr(start, length)

The slice() Method


var str = "Amrit, Arora, Karan";
var res = str.slice(7, 12);

The substring() Method: substring() is similar to slice().

The difference is that substring() cannot accept negative indexes.

var str = "Amrit, Arora, Karan";


var res = str.substring (7, 12);

The substr() Method : substr() is similar to slice().

The difference is that the second parameter specifies the length of the extracted part.

var str = "Amrit, Arora, Karan";


var res = str.substr(7, 5);

Replacing String Content

str = "Please visit XYZ!";


var n = str.replace("XYZ", "ABC");

By default, the replace() function replaces only the first match. It returns a new string and it is
case sensitive.

To replace case insensitive, use a regular expression with an /i flag (insensitive):

str = "Please visit Microsoft!";


var n = str.replace(/MiCroSoft/i, "JavaScript");

To replace all matches, use a regular expression with a /g flag (global match):

str = "Please visit Microsoft and Microsoft!";


var n = str.replace(/Microsoft/g, " JavaScript");
Converting to Upper and Lower Case
A string is converted to upper case with toUpperCase():
var text1 = "Hello World!"; // String
var text2 = text1.toUpperCase(); // text2 is text1 converted to upper

A string is converted to lower case with toLowerCase():

var text1 = "Hello World!"; // String


var text2 = text1.toLowerCase(); // text2 is text1 converted to lower

The concat() Method

var text1 = "Hello";


var text2 = "World";
var text3 = text1.concat(" ", text2);

The concat() method can be used instead of the plus operator. These two lines do the same:

var text = "Hello" + " " + "World!";


var text = "Hello".concat(" ", "World!");

All string methods return a new string. They don't modify the original string.

Extracting String Characters

There are 2 safe methods for extracting string characters:

 charAt(position)
 charCodeAt(position)

1. var str = "HELLO WORLD";


str.charAt(0); // returns H

2. var str = "HELLO WORLD";

str.charCodeAt(0); // returns 72

Accessing a String as an Array is Unsafe


var str = "HELLO WORLD";

str[0]; // returns H

This is unsafe and unpredictable:

 It does not work in all browsers (not in IE5, IE6, IE7)


 It makes strings look like arrays (but they are not)
 str[0] = "H" does not give an error (but does not work)

If you want to read a string as an array, convert it to an array first.


Converting a String to an Array

A string can be converted to an array with the split() method:

var str = "a,b,c,d,e,f";


var arr = str.split(",");
document.write(arr[0] + "<br/>" +arr[1]);

If the separator is omitted, the returned array will contain the whole string in index [0].

If the separator is "", the returned array will be an array of single characters:

<script>
var str = "Hello";
var arr = str.split("");
var text = "";
var i;
for (i = 0; i < arr.length; i++) {
document.write(arr[i] + "<br>");
}
</script>

localeCompare () : This method returns a number indicating whether a reference string comes
before or after or is the same as the given string in sorted order.
Return Value
 0 : If the string matches 100%.
 1 : no match, and the parameter value comes before the string object's value in the locale
sort order
 -1 : no match, and the parameter value comes after the string object's value in the local
sort order

<html>
<body>
<script type="text/javascript">
var str1 = new String( "This is beautiful string" );
var index = str1.localeCompare( "XYZ" );
document.write("localeCompare first :" + index );
document.write("<br />" );
var index = str1.localeCompare( "AbCD" );
document.write("localeCompare second :" + index );
</script>
</body>
</html>

Output:
localeCompare first :-1
localeCompare second :1
italics( )
<html>
<head>
<title>JavaScript String italics() Method</title>
</head>
<body>
<script type="text/javascript">
var str = new String("Hello world");
alert(str.italics( ));
</script>
</body>
</html>

Output
<i>Hello world</i>

JavaScript Math Object


The JavaScript Math object allows you to perform mathematical tasks on numbers.

1. Math.PI
<script>
document.write(Math.PI);
</script>

2. Math.round()
<script>
document.write( Math.round(4.4));
</script>

3. Math.pow()
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.pow(8,2);
</script>

4. Math.sqrt()
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.sqrt(64);
</script>

5. Math.abs() : returns the absolute (positive) value of x


6. Math.ceil(x) returns the value of x rounded up to its nearest integer.
7. Math.floor(x) returns the value of x rounded down to its nearest integer.
8. Math.sin()

<body>

<p>Math.sin(x) returns the sin of x (given in radians):</p>


<p>Angle in radians = (angle in degrees) * PI / 180.</p>

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

<script>
document.getElementById("demo").innerHTML =
"The sine value of 90 degrees is " + Math.sin(90 * Math.PI / 180);
</script>

</body>

9. Math.cos(x) returns the cosine (a value between -1 and 1) of the angle x (given in
radians).

10. Math.min() and Math.max()

Math.min() and Math.max() can be used to find the lowest or highest value in a list of
arguments

<script>

document.write(Math.min(0, 150, 30, 20, -8, -200));

</script>

11. Math.random()

<script>

document.getElementById("demo").innerHTML = Math.random();

</script>

12. Math Properties (Constants)

JavaScript provides 8 mathematical constants that can be accessed with the Math object:

<script>
document.getElementById("demo").innerHTML =
"<p><b>Math.E:</b> " + Math.E + "</p>" +
"<p><b>Math.PI:</b> " + Math.PI + "</p>" +
"<p><b>Math.SQRT2:</b> " + Math.SQRT2 + "</p>" +
"<p><b>Math.SQRT1_2:</b> " + Math.SQRT1_2 + "</p>" +
"<p><b>Math.LN2:</b> " + Math.LN2 + "</p>" +
"<p><b>Math.LN10:</b> " + Math.LN10 + "</p>" +
"<p><b>Math.LOG2E:</b> " + Math.LOG2E + "</p>" +
"<p><b>Math.Log10E:</b> " + Math.LOG10E + "</p>";
</script>

13.
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
atan2(y, x) Returns the arctangent of the quotient of its arguments
exp(x) Returns the value of Ex
log(x) Returns the natural logarithm (base E) of x
tan(x) Returns the tangent of an angle

JavaScript Arrays
JavaScript arrays are used to store multiple values in a single variable.

Creating an Array

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

Syntax:

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

Example 1:
<script>
var cars = ["Audi", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>

Spaces and line breaks are not important. A declaration can span multiple lines:
var cars = [
"Audi",
"Volvo",
"BMW"
];

Using the JavaScript Keyword new


<script>
var cars = new Array("Saab", "Volvo", "BMW");
document.write(cars);
</script>

Access the Elements of an Array

You refer to an array element by referring to the index number.


This statement accesses the value of the first element in cars:

var name = cars[0];

This statement modifies the first element in cars:

cars[0] = "Opel";

Note: [0] is the first element in an array. [1] is the second. Array indexes start with 0.

Access the Full Array : SEE EXAMPLE 1

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:

<script>
var person = ["John", "Doe", 46];
document.write(person);
</script>

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;

The length Property

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

<script>
var fruits = ["B", "O", "A", "M"];
document.write(fruits.length);
</script>
Looping Array Elements
<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.write(text);
</script>

Example 1:
<html>
<title>Week Day</title>
<body>
<script language="Javascript">
var no = prompt("Enter the day number : ");
var weekday = new Array(7);

weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
weekday[7] = "Sunday";
var n = weekday[no];

alert("Day is : " + n);


</script>

</body>

</html>

Example 2:
<html>
<head>
<title>Sum , Average , largest</title>
<script language="Javascript">
function check(){
var ob = new Array(2);
for(i=0;i<3;i++)
{
ob[i]=prompt("Enter Value ");
ob[i]=parseInt(ob[i]);
}
var sum=0,max=0;
for(j=0;j<3;j++){
sum=sum+ob[j];
if(ob[j]>=max){
max= ob[j];
}
}
alert("Sum is "+ sum +" \nAverage is : "+ (sum/3) + " \nLargest is : " +
max);
}
</script>
</head>
<body>
<input type="Submit" value="Check" onclick="check()">
</body>
</html>

Array Methods

Here is a list of the methods of the Array object along with their description.

Sr.No Method & Description


concat()
1
Returns a new array comprised of this array joined with other array(s) and/or value(s).
join()
2
Joins all elements of an array into a string.
pop()
3
Removes the last element from an array and returns that element.
push()
4
Adds one or more elements to the end of an array and returns the new length of the array.
reverse()
5
Reverses the order of the elements of an array -- the first becomes the last, and the last
becomes the first.
shift()
6
Removes the first element from an array and returns that element.
slice()
7
Extracts a section of an array and returns a new array.
sort()
8
Sorts the elements of an array
splice()
9
Adds and/or removes elements from an array.
unshift()
10
Adds one or more elements to the front of an array and returns the new length of the
array.
delete
11
elements can be deleted by using the JavaScript operator delete
toString()
12
converts an array to a string of (comma separated) array values.

Example 1: Merging Two and Three Arrays

1. <script>
var Fruits = ["Apple", "Mango"];
var Vegetables = ["Potatos", "Beans", "Carrots"];
var Fruits = Fruits.concat(Vegetables);

document.write(Fruits);
</script>

2. <script>
var arr1 = ["Cecilie", "Lone"];
var arr2 = ["Emil", "Tobias", "Linus"];
var arr3 = ["Robin", "Morgan"];

var myChildren = arr1.concat(arr2, arr3);

document.write(myChildren);
</script>

3. <script>
var arr1 = ["Cecilie", "Lone"];
var myChildren = arr1.concat(["Emil", "Tobias", "Linus"]);
document.write(myChildren);
</script>

Example 2:
<p>The toString() method returns an array as a comma separated string:</p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits.toString());

</script>

Example 3:
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits.join(" * "));
</script>

Example 4:
<p>The pop() method removes the last element from an array.</p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits + "<br/>");
fruits.pop();
document.write(fruits);
</script>

OR

<p>The pop() method removes the last element from an array.</p>


<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits + "<br/>");
var ele = fruits.pop();

document.write("Deleted Element is : " + ele);


</script>

Example 5:
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits + "<br/>");

fruits.push("Kiwi");

document.write(fruits);
</script>

Example 6:
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits + "<br/>");

fruits.shift();

document.write(fruits);
</script>

OR

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits + "<br/>");
document.write("No.of elements : " + ele);

var ele = fruits.shift();


document.write(fruits + "<br/>");
document.write("No.of elements : " + ele);

</script>

Example 7:

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits + "<br/>");
document.write("No.of elements : " + fruits.length + "<br/>");

var ele = fruits.unshift("Kiwi");

document.write(fruits + "<br/>");
document.write("No.of elements : " + ele);

</script>

Example 8:
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits + "<br/>");
document.write("No.of elements : " + fruits.length + "<br/>");

delete fruits[2];

document.write(fruits + "<br/>");
document.write("No.of elements : " + fruits.length);

</script>

Example 9.1:
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits + "<br/>");
document.write("No.of elements : " + fruits.length + "<br/>");

fruits.splice(2, 0, "Lemon", "Kiwi");

document.write(fruits + "<br/>");
document.write("No.of elements : " + fruits.length);

</script>

Example 9.2:
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits + "<br/>");
document.write("No.of elements : " + fruits.length + "<br/>");

fruits.splice(0, 1);

document.write(fruits + "<br/>");
document.write("No.of elements : " + fruits.length);

</script>

Example 10:
1. <script>
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(3);
document.write(fruits + "<br><br>" + citrus);
</script>

2. <script>
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1,3);
document.write(fruits + "<br><br>" + citrus);
</script>

Example 11:

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits + "<br/>");

fruits.sort();
document.write(fruits);

Example 12:

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits + "<br/>");
fruits.reverse();
document.write(fruits);

</script>

Example 13: Sorting Numeric Array

<script>
var points = [40, 100, 1, 5, 25, 10];
document.write(points+"<br/>");

points.sort(function(a, b){return a - b});


document.write(points);

</script>
JavaScript Dates
The Date object lets you work with dates (years, months, days, hours, minutes, seconds, and
milliseconds).

JavaScript Date Formats

A JavaScript date can be written as a string:

Tue Apr 03 2018 13:50:18 GMT+0530 (India Standard Time)

or as a number:

1522743618744

Dates written as numbers, specify the number of milliseconds since January 1, 1970, 00:00:00.

Displaying Dates

<html>

<body>

<script>

document.write( Date());

</script>

</body>

</html>

Creating Date Objects

Date objects are created with the new Date() constructor. It creates a new date object with the
current date and time.

There are 4 ways of initiating a date:

new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Example 1:
<script>
var d = new Date();
document.write( d );
</script>

JavaScript Date Output

Independent of input format, JavaScript will (by default) output dates in full text string format:

Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)

Example 2:

<script>
var d = new Date("October 13, 2014 11:13:00");
document.write( d );
</script>

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

Example 4:

<script>
var d = new Date(99,5,24,11,33,30,0);
document.write( d );
</script>

Example 5:

<script>
var d = new Date(99,5,24);
document.write( d );
</script>

The toDateString() method converts a date to a more readable format:


<script>
var d = new Date();
document.write( d.toDateString() );
</script>
JavaScript Date Input

There are generally 4 types of JavaScript date input formats:

Type Example
ISO Date "2015-03-25" (The International Standard)
Short Date "03/25/2015"
Long Date "Mar 25 2015" or "25 Mar 2015"
Full Date "Wednesday March 25 2015"

The ISO format follows a strict standard in JavaScript.

The other formats are not so well defined and might be browser specific.

Example:
<body>

<h2>JavaScript ISO Dates</h2>

<script>
document.write(new Date("2015-03-25"));
</script>

</body>

Example:
ISO Dates (Year and Month)

ISO dates can be written without specifying the day (YYYY-MM):

var d = new Date("2015-03");

ISO Dates (Date-Time)

ISO dates can be written with added hours, minutes, and seconds (YYYY-MM-
DDTHH:MM:SSZ):

<body>

<h2>JavaScript ISO Dates</h2>

<p>Separate date and time with a capital T.</p>

<p>Indicate UTC time with a capital Z.</p>

<script>
document.write(new Date("2015-03-25T12:00:00Z"));
</script>
</body>
Output:

JavaScript ISO Dates

Separate date and time with a capital T.

Indicate UTC time with a capital Z.

Wed Mar 25 2015 17:30:00 GMT+0530 (India Standard Time)

JavaScript Short Dates.

Short dates are written with an "MM/DD/YYYY" syntax like this:

var d = new Date("03/25/2015");

JavaScript Long Dates.

Long dates are most often written with a "MMM DD YYYY" syntax like this:

1. var d = new Date("Mar 25 2015");


2. var d = new Date("25 Mar 2015");
3. var d = new Date("January 25 2015");
4. var d = new Date("JANUARY, 25, 2015");

JavaScript Full Date

JavaScript will accept date strings in "full JavaScript format":

<script>
document.write(new Date("Wed Mar 25 2015 09:56:24 GMT+0100 (Indian Standard Time)"));
</script>
Associative Array

Associative arrays give you a way to label your array item keys instead of them being numbered
in the way that array elements are usually numerically indexed by default. The key is directly
associated to its value in a meaningful way.

var myArray = {user:"Joe", age:24, height:"70in"};

document.write(myArray["user"]+" is "+myArray["age"]+" years old.<br />");


document.write(myArray["user"]+" is "+myArray["height"]+" tall.");

Multidimensional Array
A multidimensional array is an array that is holding multiple arrays that can be of various types.

var myArray = new Array(


["Vanilla","Chocolate","Strawberry"],
["Cat","Dog","Fox","Mouse","Owl"],
["HTML","CSS","Javascript","PHP"]
);
document.write(myArray[0]+"<br />");
document.write(myArray[1]+"<br />");
document.write(myArray[2]+"<br />");

OR

var myArray = new Array(


["Vanilla","Chocolate","Strawberry"],
["Cat","Dog","Fox","Mouse","Owl"],
["HTML","CSS","Javascript","PHP"]
);
for(var i = 0; i < myArray.length; i++) {
for(var itm in myArray[i]) {
document.write(myArray[i][itm]+"<br />");
}
}

Example 1: Linear Search


<html>

<head>
<title>Search an element</title>
<script language="JavaScript">
function find() {
var n = prompt("Enter size of array");
ob = new Array(n);
for (i = 0; i < n; i++) {
ob[i] = prompt("enter Value at location " + i + " of the array");
}
var find = prompt("Enter value to find");
for (j = 0; j < n; j++) {
if (ob[j] == find) {
alert("Value " + ob[j]+ " found at " + j + " location " );
break;
}
if(j==n)
alert("Value Not Found");
}

}
</script>
</head>

<body bgcolor="">
<input type="submit" name="submit" onclick="find()" value="Search">
</body>

Example: voting eligibility

<html>

<head>
<script language="javascript">
function check() {
var age;
age = document.sub.age.value;
if (age < 18) {
document.sub.output.value = "not eligible to vote";
} else if (age >= 18) {
document.sub.output.value = "eligible to vote";
}
}
</script>

</head>

<body bgcolor="AliceBlue">
<form name="sub">
<table cellpadding="10" bgcolor="Khaki" align="center" cellspacing="2" border=1
style="border-collapse:collapse;">
<tr>
<th align="center" colspan=2>
<h1>Subroutine in JS</h1>
</th>
</tr>
<tr>
<td>Enter your age:</td>
<td><input type="number" id="age"></td>
</tr>
<tr>
<td colspan="2"><input type="button" value="check" onClick=check()></td>
</tr>
<tr>
<td>Result:</td>
<td><input type="text" id="output"></input></td>
</tr>

</table>
</form>
</body>

</html>

Example: program to check whether a textbox is empty or not.

<html>
<head>
<title>
program to check whether a textbox is empty or not.
</title>
<script language="javascript">
function check()
{
var a=document.frm.textbox.value;
if(a.length===0)
{
alert("textbox is empty")
}
else
{
alert("welcome")
}
}
</script>
</head>

<body>
<form name="frm">
<table width=400px border=1 align="center">
<tr>
<td align="center">
<input type="text" name="textbox">
</td>
</tr>
<tr>
<td align="center">
<input type="button" value="check" onclick="check();">
</td>
</tr>
</body>
</html>

Example: Changing BGCOLOR

<html>
<head>
<title>
BGCOLOR
</title>
</head>
<body>
<script language="Javascript">
function bg(){
var a=frm.col.value;
document.bgColor=a;
}
</script>

<form name=frm>
Enter the color you want as BackGround : &nbsp
<input type=text id=col><br>
<input type=button value=Change onclick=bg()>
</body>
</html>

Example 2:
</html>
<script type="text/javascript">
var colors = new Array();
colors[0] = "red"; colors[1] = "green";
colors[2] = "blue"; colors[3] = "orange";
colors[4] = "magenta"; colors[5] = "cyan";
for (var i in colors) {
document.write("<div style=\"background-color:"
+ colors[i] + ";\">"
+ colors[i] + "</div>\n");
}
</script>
JavaScript Events
JavaScript's interaction with HTML is handled through events that occur when the user or the
browser manipulates a page. When the page loads, it is called an event. When the user clicks a
button, that click too is an event. Other examples include events like pressing any key,
closing a window, resizing a window, etc. 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">

Events are a part of the Document Object Model (DOM) Level 3 and every HTML
element contains a set of events which can trigger JavaScript Code.

Event handlers

An event handler allows you to execute code when an event occurs.

Events are generated by the browser when the user clicks an element, when the page loads,
when a form is submitted, etc.

Example

A header changes when the user clicks it:

<h1 onclick="this.innerHTML='Ooops!'">Click on this text</h1>

Example 1:
<html>
<body>

<button onclick="document.getElementById('demo').innerHTML=Date()">The time


is?</button>

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

</body>
</html>

Example 2: Following code changes the content of its own element


<html>
<body>

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

</body>
</html>

Example 3: JavaScript code is often several lines long. It is more common to see event
attributes calling functions like
<html>
<body>

<p>Click the button to display the date.</p>

<button onclick="displayDate()">The time is?</button>

<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>

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

</body>
</html>

Common HTML Events


Here is a list of some common HTML events

Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page
onsubmit occurs when you try to submit a form.
onmouseup a user releases a mouse-button
onmousedown a user presses a mouse-button
onkeyup a keyboard key is released
ondblclick() Executes on double click.
Event handlers can be used to handle, and verify, user input, user actions, and browser actions:

 Things that should be done every time a page loads


 Things that should be done when the page is closed
 Action that should be performed when a user clicks a button
 Content that should be verified when a user inputs data

onsubmit Event type: onsubmit is an event that occurs when you try to submit a form. You
can put your form validation against this event type.
Example:
<html>
<body>

<p>When you submit the form, a function is triggered which alerts some text.</p>

<form action="/action_page.php" onsubmit="myFunction()">


Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

<script>
function myFunction() {
alert("The form is submitted");
}
</script>

</body>
</html>

onchange Event type: The onchange event occurs when the value of an element has been
changed. For radio buttons and checkboxes, the onchange event occurs when the checked state
has been changed.

Example 1:
<html>
<body>

<p>Select a new car from the list.</p>

<select id="mySelect" onchange="myFunction()">


<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>

<p>When you select a new car, a function is triggered which outputs the value of the selected
car.</p>
<p id="demo"></p>

<script>
function myFunction() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
</script>

</body>
</html>

Example 2:
<html>
<body>

<p>Modify the text in the input field, then click outside the field to fire the onchange
event.</p>

Enter some text: <input type="text" name="txt" value="Hello"


onchange="myFunction(this.value)">

<script>
function myFunction(val) {
alert("The input value has changed. The new value is: " + val);
}
</script>

</body>
</html>

onmouseover and onmouseout Event: The onmouseover event occurs when the mouse
pointer is moved onto an element, or onto one of its children. The onmouseout event occurs
when the mouse pointer is moved out of an element, or out of one of its children. These event
are often used together, which occurs when the pointer is moved onto an element, or onto one of
its children.
Example 1:
<html>
<body>

<img onmouseover="bigImg(this)" onmouseout="normalImg(this)" border="0"


src="smiley.gif" alt="Smiley" width="32" height="32">

<p>The function bigImg() is triggered when the user moves the mouse pointer over the
image.</p>
<p>The function normalImg() is triggered when the mouse pointer is moved out of the
image.</p>

<script>
function bigImg(x) {
x.style.height = "64px";
x.style.width = "64px";
}

function normalImg(x) {
x.style.height = "32px";
x.style.width = "32px";
}
</script>

</body>
</html>

Example 2:
<html>
<body>

<p>This example uses the HTML DOM to assign an "onmouseover" and "onmouseout" event
to a h1 element.</p>

<h1 id="demo">Mouse over me</h1>

<script>
document.getElementById("demo").onmouseover = function() {mouseOver()};
document.getElementById("demo").onmouseout = function() {mouseOut()};

function mouseOver() {
document.getElementById("demo").style.color = "red";
}

function mouseOut() {
document.getElementById("demo").style.color = "Green";
}
</script>

</body>
</html>

onkeydown Event: The onkeydown event occurs when the user is pressing a key (on the
keyboard).

Example 1:
<html>
<body>

<p>A function is triggered when the user is pressing a key in the input field.</p>

<input type="text" onkeydown="myFunction()">

<script>
function myFunction() {
alert("You pressed a key inside the input field");
}
</script>

</body>
</html>

Example 2:

<html>
<body>

<p>This example uses the HTML DOM to assign an "onkeydown" event to an input
element.</p>

<p>Press a key inside the text field to set a red background color.</p>

<input type="text" id="demo">

<script>
document.getElementById("demo").onkeydown = function() {myFunction()};

function myFunction() {
document.getElementById("demo").style.backgroundColor = "red";
}
</script>

</body>
</html>

onload event: The onload event occurs when an object has been loaded. onload is most often
used within the <body> element to execute a script once a web page has completely loaded all
content (including images, script files, CSS files, etc.). The onload event can be used to check
the visitor's browser type and browser version, and load the proper version of the web page
based on the information. The onload event can also be used to deal with cookies

Example 1:

<html>
<body>
<p>This example demonstrates how to assign an "onload" event to an iframe element.</p>
<iframe onload="myFunction()" src="/default.asp"></iframe>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Iframe is loaded.";
}
</script>
</body>
</html>
Example 2:

<html>
<body>
<p>This example uses the HTML DOM to assign an "onload" event to an iframe element.</p>
<iframe id="myFrame" src="/default.asp"></iframe>

<p id="demo"></p>
<script>
document.getElementById("myFrame").onload = function() {myFunction()};

function myFunction() {
document.getElementById("demo").innerHTML = "Iframe is loaded.";
}
</script>

</body>
</html>

onmouseup and onmousedown Event: These events are executed when a user releases a
mouse-button or presses down mouse button.

Example:
<html>
<head>
<script type="text/javascript">
function lighton()
{
document.getElementById('myimage').src="bulbon.gif";
}
function lightoff()
{
document.getElementById('myimage').src="bulboff.gif";
}
</script>
</head>

<body>
<img id="myimage" onmousedown="lighton()"
onmouseup="lightoff()"
src="bulboff.gif" width="100"
height="180">
<p>Click to turn on the light</p>
</body>
</html>

ondblclick(): Executes on double click.


Example 1:
<html>
<head>
<script type="text/javascript">
function gettip(txt)
{
document.getElementById('tip').innerHTML='W3C is about WEB standards, and scripting
technologies for the World Wide Web';
}
</script>
</head>

<body>

<p>Double click the "W3C"</p>


<table>
<tr>
<th ondblclick="gettip()" valign="top"> W3C </th>
<th id="tip"> </th>
</tr>
</table>

</body>
</html>

You might also like