Unit-2-Javascript Theory
Unit-2-Javascript Theory
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.
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.
<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>
</body>
</html>
3. JavaScript in <body>
<html>
<body>
<h2>JavaScript in Body</h2>
<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>
<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>
</body>
</html>
<p>In this case JavaScript changes the src (source) attribute of an image.</p>
</body>
</html>
3. JavaScript Can Change HTML Styles (CSS)
<html>
<body>
1. <script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
2. <script>
document.write(5 + 6);
</script>
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:
<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.
<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
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 />";
</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 −
Ex: (A & B) is 2.
| (BitWise OR)
Ex: (A | B) is 3.
^ (Bitwise XOR)
Ex: (A ^ B) is 1.
~ (Bitwise Not)
4 It is a unary operator and operates by reversing all the bits in the operand.
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 />";
</body>
</html>
5. Assignment Operators
1 Assigns values from the right side operand to the left side operand
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.
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
</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.
<script type="text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
JavaScript Selection Statements
1. if...else Statement
if statement
if...else statement
if...else if... statement.
Example 1:
<html>
<body>
<script type="text/javascript">
<!--
var age = 20;
</body>
</html>
Example 2:
<html>
<body>
<script type="text/javascript">
<!--
var age = 15;
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{
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;
</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.
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 ");
document.write("Loop stopped!");
//-->
</script>
</body>
</html>
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;
</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.
<script type="text/javascript">
<!--
var count;
document.write("Starting Loop" + "<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 /> ");
<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
</body>
</html>
Output
Entering the loop
2
3
4
5
Exiting the loop!
<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
if (x == 5){
continue; // skip rest of the loop body
}
document.write( x + "<br />");
}
</body>
</html>
<script type="text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name
</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
</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
<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
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>
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.
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.
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.
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
var book = new Object(); // Create 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;
}
<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>
</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());
</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
There are 3 JavaScript methods that can be used to convert variables to numbers:
These methods are not number methods, but global JavaScript methods.
Global Methods
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
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);
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:
slice(start, end)
substring(start, end)
substr(start, length)
The difference is that the second parameter specifies the length of the extracted part.
By default, the replace() function replaces only the first match. It returns a new string and it is
case sensitive.
To replace all matches, use a regular expression with a /g flag (global match):
The concat() method can be used instead of the plus operator. These two lines do the same:
All string methods return a new string. They don't modify the original string.
charAt(position)
charCodeAt(position)
str.charCodeAt(0); // returns 72
str[0]; // returns H
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>
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>
<body>
<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).
Math.min() and Math.max() can be used to find the lowest or highest value in a list of
arguments
<script>
</script>
11. Math.random()
<script>
document.getElementById("demo").innerHTML = Math.random();
</script>
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
Syntax:
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"
];
cars[0] = "Opel";
Note: [0] is the first element in an array. [1] is the second. Array indexes start with 0.
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>
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 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;
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];
</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.
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"];
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
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);
</script>
Example 7:
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits + "<br/>");
document.write("No.of elements : " + fruits.length + "<br/>");
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/>");
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>
<script>
var points = [40, 100, 1, 5, 25, 10];
document.write(points+"<br/>");
</script>
JavaScript Dates
The Date object lets you work with dates (years, months, days, hours, minutes, seconds, and
milliseconds).
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>
Date objects are created with the new Date() constructor. It creates a new date object with the
current date and time.
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>
Independent of input format, JavaScript will (by default) output dates in full text string format:
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>
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 other formats are not so well defined and might be browser specific.
Example:
<body>
<script>
document.write(new Date("2015-03-25"));
</script>
</body>
Example:
ISO Dates (Year and Month)
ISO dates can be written with added hours, minutes, and seconds (YYYY-MM-
DDTHH:MM:SSZ):
<body>
<script>
document.write(new Date("2015-03-25T12:00:00Z"));
</script>
</body>
Output:
Long dates are most often written with a "MMM DD YYYY" syntax like this:
<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.
Multidimensional Array
A multidimensional array is an array that is holding multiple arrays that can be of various types.
OR
<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>
<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>
<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>
<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 :  
<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.
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
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
Events are generated by the browser when the user clicks an element, when the page loads,
when a form is submitted, etc.
Example
Example 1:
<html>
<body>
<p id="demo"></p>
</body>
</html>
</body>
</html>
Example 3: JavaScript code is often several lines long. It is more common to see event
attributes calling functions like
<html>
<body>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>
</body>
</html>
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:
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>
<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>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>
<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>
<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>
<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>
<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>
<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>
<body>
</body>
</html>