Unit 3- JavaScript
Unit 3- JavaScript
JAVASCRIPT
1. INTRODUCTION
a. Scripting language
b. Client-side language
c. Object-based language i.e. does not have polymorphism or inheritance or both
d. Interpreted language. The browser has the interpreter.
e.Light weighted and does not require server interaction. So, the response is
faster.
f.No API for networking, don't have the concept of file handling, multithreading,
and multi-processing.
g. User inputs can be validated before sending the data to the server.
2. INCORPORATING JAVASCRIPT
i. JS Code is written with the <script> tag
<script type="text/javascript">
document.write("Rohit")
</script>
ii. Two ways:
a. Internally: embedding code in HTML. There is only one file i.e. file with a
.html extension
i. in the body tag
ii. in the head tag
b.Externally: in separate .js file. There will be two separate files. one with .js
extension and other .html
3. JAVASCRIPT COMMENTS
a. Single line comments: //
b. Multiple line comments: /* */
4. VARIABLE
var a = 10 or a = 1.02
1. CONVENTIONS
a. Names must start with a letter(a-z, A-Z), _ or $
b. 0-9
c. Case sensitive. a and A are different.
We can create a number object using the ‘new’ operator and the Number()
constructor:
var num1= new Number(5);
console.log(num1); // This will return 5
typeof(num1); // This will return ‘number’
String:
The string data type in JavaScript can be any group of characters enclosed by
single or double.
var str1 = “This is a string1”; // This is a string primitive type or string literal
var str2= ‘This is a string2’;
The variable ‘a’ has been declared but hasn’t been assigned a value yet.
We can assign a value to a:
a=5;
console.log(a); // This will return 5
null:
The null in JavaScript is a data type represented by only one value, the
‘null’ itself.
A null value means no value.
You can assign null to a variable to denote that currently; the variable does not
have any value but will have it later.
A null value evaluates to false in a conditional expression.
So, you don't have to use comparison operators like === or !== to check for
null values.
5.2. NON-PRIMITIVE DATA TYPES
The non-primitive data types are as follows:
Data Description
Type
Object represents instance through which we can access members
Array represents a group of similar values
Date represents properties of date
6. OPERATORS
JavaScript operators are symbols that are used to perform operations on operands.
For example:
var sum=10+20;
Here, + is the arithmetic operator and = is the assignment operator.
There are the following types of operators in JavaScript.
a) Arithmetic Operators
b)Comparison (Relational) Operators
c) Bitwise Operators
d)Logical Operators
e) Assignment Operators
f) Special Operators
6.1. ARITHMETIC OPERATORS
Arithmetic operators are used to performing arithmetic operations on the
operands. The following operators are known as JavaScript arithmetic operators.
Operator Description
(?:) returns a value based on the condition. It is like if-else.
delete deletes a property from the object.
in checks if the object has the given property
instanceof checks if the object is an instance of a given type
new creates an instance (object)
typeof checks the type of object.
7. CONDITIONAL STATEMENTS
1. IF-ELSE
The if-else statement is used to execute the code whether the condition is true or
false. There are three forms of if statement in JavaScript.
1.If Statement
2.If else statement
3.if else if statement
7.1.1. IF STATEMENT
It evaluates the content only if the expression is true. The syntax of the JavaScript
if statement is given below.
if(expression){
//content to be evaluated
}
Let’s see the simple example of if statement in JavaScript.
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
Output of the above example
value of a is greater than 10
7.1.2. IF...ELSE STATEMENT
It evaluates the content whether the condition is true or false. The syntax of the
JavaScript if-else statement is given below.
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
Let’s see the example of if-else statement in JavaScript to find out the even or
odd number.
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
function myFunction(y) {
return y * y;
}
</script>
10.6. FUNCTION WITH RETURN VALUE
We can call a function that returns a value and use it in our program. Let’s see
the example of a function that returns a value.
<script>
function getInfo(){
return "hello ! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
Output of the above example
hello! How r u?
11. DISPLAY POPUP MESSAGE BOX
JavaScript provides different built-in functions to display popup messages for
different purposes e.g. to display a simple message or display a message and
take the user's confirmation on it or display a popup to take a user's input value.
11.1. ALERT BOX
Use alert() function to display a popup message to the user. This popup will
have OK button to close the popup.
alert("This is alert box!"); // display string message
alert(100); // display 100
The alert function can display messages of any data type e.g., string, number,
boolean, etc. There is no need to convert a message to string type.
11.2. CONFIRM BOX
Sometimes you need to take the user's confirmation to proceed. For example,
you want to take the user's confirmation before saving updated data or deleting
existing data. In this scenario, use JavaScript built-in function confirm(). The
confirm() function displays a popup message to the user with two
buttons, OK and Cancel. You can check which button the user has clicked and
proceed accordingly.
<script>
if (confirm("Do you want to save changes?") == true) {
document.write("Data saved successfully!")
} else {
document.write("Save Cancelled!")
}
</script>
11.3. PROMPT BOX
Sometimes you may need to take the user's input to do further actions on a web
page. For example, you want to calculate EMI based on users' preferred tenure
of the loan. For this kind of scenario, use JavaScript built-in function prompt().
The prompt function takes two string parameters. The first parameter is the
message to be displayed and the second parameter is the default value which
will be in the input text when the message is displayed.
Syntax:
Example:
<script>
var tenure = prompt("Please enter preferred tenure in years", "15");
if (tenure != null) {
alert("You have entered " + tenure + " years" );
}
</script>
As you can see in the above example, we have specified a message as the first
parameter and default value "15" as the second parameter. The prompt function
returns a user-entered value. If the user has not entered anything then it returns
null. So, it is recommended to check null before proceeding.
Note:
The alert, confirm and prompt functions are global functions. So it can also be
called using window object like window.alert(), window.confirm() and
window.prompt().
Points to Remember:
1. Popup message can be shown using global functions - alert(), confirm() and
prompt().
2. alert() function displays popup message with 'Ok' button.
3. confirm() function display popup message with 'Ok' and 'Cancel' buttons. Use
confirm() function to take the user's confirmation to proceed.
4. prompt() function enables you to take the user's input with 'Ok' and 'Cancel'
buttons. prompt() function returns value entered by the user. It returns null if
the user does not provide any input value.
12. JAVASCRIPT USER-DEFINED OBJECTS
A JavaScript object is an entity having state and behavior (properties and
method). For example, car, pen, bike, chair, glass, keyboard, monitor, etc.
JavaScript is an object-based language. Everything is an object in JavaScript.
1. CREATING OBJECTS
There are 3 ways to create objects.
i. By object literal
ii. By creating instance of Object directly (using the new keyword)
iii. By using an object constructor (using the new keyword)
BY OBJECT LITERAL
The syntax of creating an object using object literal is given below:
object = {property1:value1, property2:value2.....propertyN:valueN}
property and value pair are separated by: (colon).
Let’s see the simple example of creating object in JavaScript.
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
<script>
var arr1=["C","C++","Python"];
var arr2=["Java","JavaScript","Android"];
var result=arr1.concat(arr2);
document.writeln(result);
</script>
Output:
C,C++,Python,Java,JavaScript,Android
b. pop() method
The JavaScript array pop() method removes the last element from the given
array and returns that element. This method changes the length of the original
array.
Syntax:
The pop() method is represented by the following syntax:
array.pop()
Return
The last element of the given array.
Example 1
Here, we will pop an element from the given array.
<script>
var arr=["AngularJS","Node.js","JQuery"];
document.writeln("Orginal array: "+arr+"<br>");
document.writeln("Extracted element: "+arr.pop()+"<br>");
document.writeln("Remaining elements: "+ arr);
</script>
Output:
Orginal array: AngularJS,Node.js,JQuery
Extracted element: JQuery
Remaining elements: AngulaJS,Node.js
Example 2
In this example, we will pop all the elements from the given array.
<script>
var arr=["AngulaJS","Node.js","JQuery"];
var len=arr.length;
for(var x=1;x<=len;x++)
{
document.writeln("Extracted element: "+arr.pop()+"<br>");
}
</script>
Output:
Extracted element: JQuery
Extracted element: Node.js
Extracted element: AngulaJS
c. push() method
The JavaScript array push() method adds one or more elements to the end of
the given array. This method changes the length of the original array.
Syntax
The push() method is represented by the following syntax:
array.push(element1,element2....elementn)
Parameter
element1, element2....elementn - The elements to be added.
Return
The original array with added elements.
Let's see some examples of push() method
Example 1
Here, we will add an element in the given array.
<script>
var arr=["AngularJS","Node.js"];
arr.push("JQuery");
document.writeln(arr);
</script>
Output:
AngularJS,Node.js,JQuery
Example 2
Let's see an example to add more than one element in the given array.
<script>
var arr=["AngularJS","Node.js"];
document.writeln("Length before invoking push(): "+arr.length+"<br>");
arr.push("JQuery","Bootstrap");
document.writeln("Length after invoking push(): "+arr.length+"<br>");
document.writeln("Update array: "+arr);
</script>
Output:
Length before invoking push(): 2
Length after invoking push(): 4
Update array: AngularJS,Node.js,JQuery,Bootstrap
Example 2
Let's see one more example to extract various element from the given array.
<script>
var arr=["AngularJS","Node.js","JQuery","Bootstrap"]
var result=arr.slice(0,3);
document.writeln(result);
</script>
Output:
AngularJS,Node.js,JQuery
Example 3
In this example, we will provide the negative values as index to extract elements.
<script>
var arr=["AngularJS","Node.js","JQuery","Bootstrap"]
var result=arr.slice(-4,-1);
document.writeln(result);
</script>
Output:
AngularJS,Node.js,JQuery
g. sort() method
The JavaScript array sort() method is used to arrange the array elements in some
order. By default, sort() method follows the ascending order.
Syntax
The sort() method is represented by the following syntax:
array.sort(compareFunction)
Parameter
compareFunction - It is optional. It represents a function that provides an
alternative sort order.
Return
An array of sorted elements
Example 1
Let's see a simple example to sort the array of string elements.
<script>
var arr=["AngularJS","Node.js","JQuery","Bootstrap"]
var result=arr.sort();
document.writeln(result);
</script>
Output:
AngularJS,Bootstrap,JQuery,Node.js
Example 2
<script>
var arr=[2,4,1,8,5];
var result=arr.sort();
document.writeln(result);
</script>
Output:
1,2,4,5,8
console.log(names);
function len_compare(a, b){
return a.length - b.length;
}
Here:
• If a.length - b.length < 0, a comes before b. For example, "Adam" comes
before "Jeffrey" as 4 - 7 < 0.
• If a.length - b.length > 0, b comes before a. For example, "Danil" comes
after "Ben" as 5 - 3 > 0.
• If a.length - b.length == 0, their position is unchanged. For example, the relative
We can see that this results in the sorting of strings according to their length in
ascending order.
Example 4
Let's see an example to extract minimum value from an array.
<script>
var arr=[2,4,1,8,5]
var result=arr.sort(); //1,2,4,5,8
document.writeln(arr[0]);
</script>
Output:
1
Example 5
Let's see an example to extract maximum value from an array.
<script>
var arr=[2,4,1,8,5]
var result=arr.sort().reverse(); // 8,5,4,2,1
document.writeln(arr[0]);
</script>
Output:
8
h. toString() Method
The toString() method is used for converting and representing an array into
string form. It returns the string containing the specified array elements.
Commas separate these elements, and the string does not affect the original
array.
Syntax
The following syntax represents the toString() method:
array.toString()
Parameters
It does not have any parameters.
Return
It returns a string that contains all the elements of the specified array.
Example 1: Converting a given array into string form seperated by commas.
<html>
<head> <h3>Array Methods</h3> </br>
</head>
<body>
<script>
var arr=['a','b','c','d','e','f','g','h','i','j']; //array elements
var str=arr.toString(); //toString() method implementation
document.write("After converting into string: "+str);
</script>
</body>
</html>
unshift() Parameters
The unshift() method takes in an arbitrary number of elements to add to the
array.
Return value from unshift()
Returns the new (after adding arguments to the beginning of the array) length of
the array upon which the method was called.
Notes:
This method changes the original array and its length.
Example: Using unshift() method
var languages = ["JavaScript", "Python", "Java", "Lua"];
var count = languages.unshift("C++");
console.log(languages); // [ 'C++', 'JavaScript', 'Python', 'Java', 'Lua']
console.log(count); // 5
splice() Parameters
The splice() method takes in:
• start - The index from where the array is changed.
• deleteCount (optional) - The number of items to remove from start.
• item1, ..., itemN (optional) - The elements to add to the start index. If not
specified, splice() will only remove elements from the array.
Return value from splice()
Returns an array containing the deleted elements.
Note: The splice() method changes the original array.
// removing 3 elements
removed = languages.splice(2, 3);
console.log(removed2); // [ 'Lua', 'Python', 'C' ]
console.log(languages); // [ 'JavaScript', 'Java', 'C++' ]
Output
[ 'Java', 'Lua' ]
[ 'JavaScript', 'Python', 'C', 'C++' ]
[]
[ 'JavaScript', 'Java', 'Lua', 'Python', 'C', 'C++' ]
[ 'Lua', 'Python', 'C' ]
[ 'JavaScript', 'Java', 'C++' ]
Output:
hello javascript string
14.2. STRING METHODS
Let's see the list of JavaScript string methods with examples.
a) charAt(index) Method
The JavaScript String charAt() method returns the character at the given index.
<script>
var str="javascript";
document.write(str.charAt(2));
</script>
Output:
v
b) concat(str) Method
The JavaScript String concat(str) method concatenates or joins two strings.
<script>
var s1="javascript ";
var s2="concat example";
var s3=s1.concat(s2);
document.write(s3);
</script>
Output:
javascript concat example
c) indexOf(str) Method
The JavaScript String indexOf(str) method returns the index position of the
given string.
<script>
var s1="javascript from indexof";
var n=s1.indexOf("from");
document.write(n);
</script>
Output:
11
d) lastIndexOf(str) Method
The JavaScript String lastIndexOf(str) method returns the last index position of
the given string.
<script>
var s1="javascript from indexof";
var n=s1.lastIndexOf("java");
document.write(n);
</script>
Output:
16
e) toLowerCase() Method
The JavaScript String toLowerCase() method returns the given string in
lowercase letters.
<script>
var s1="JavaScript toLowerCase Example";
var s2=s1.toLowerCase();
document.write(s2);
</script>
Output:
javascript tolowercase example
f) toUpperCase() Method
The JavaScript String toUpperCase() method returns the given string in
uppercase letters.
<script>
var s1="JavaScript toUpperCase Example";
var s2=s1.toUpperCase();
document.write(s2);
</script>
Output:
JAVASCRIPT TOUPPERCASE EXAMPLE
g) slice(beginIndex, endIndex) Method
The JavaScript String slice(beginIndex, endIndex) method returns the parts of
string from given beginIndex to endIndex. In slice() method, beginIndex is
inclusive and endIndex is exclusive.
<script>
var s1="abcdefgh";
var s2=s1.slice(2,5);
document.write(s2);
</script>
Output:
cde
h) trim() Method
The JavaScript String trim() method removes leading and trailing whitespaces
from the string.
<script>
var s1=" javascript trim ";
var s2=s1.trim();
document.write(s2);
</script>
Output:
javascript trim
i) split() Method
<script>
var str="This is javascript";
document.write(str.split(" ")); //splits the given string.
</script>
15. EVENT HANDLING
1. INTRODUCTION TO EVENT HANDLING
<html>
<head>
<title>About Nodes</title>
</head>
<body>
<p>Text 1</p>
<p>Text 2</p>
</body>
</html>
16.1 HTML Document Object Model
• The DOM above contains two types of nodes: element nodes
and text nodes.
• Elements nodes are represented using angle brackets. There are
a total of 6 element
nodes: <html>, <head>, <title>, <body> and two <p> nodes.
• These element nodes are arranged to show the parent-child and
sibling relationships between them.
• Let’s consider the <head> node.
• If you study the HTML document, you can see that
the <head>…</head> tags are enclosed within
the <html> opening tag and the </html> closing tag.
• Hence, the <head> element is a child of
the <html> element. Therefore, the <head> node is placed
under the <html> node in the DOM diagram.
16.1 HTML Document Object Model
• The <body>…</body> tags are also enclosed within the
<html>…</html> tags in the HTML document.
• Hence, the <body> element is also a child of the <html>
element and is considered a sibling of the <head> element.
• Thus, the <body> node is on the same level as the <head>
node in the DOM diagram.
• Within the <head>…</head> tags in the HTML document, we
have the <title>…</title> tags.
• In other words, the <title> element is a child of the <head>
element.
• The <title> node is thus placed below the <head> node in the
DOM diagram.
• In short, if a certain HTML element is enclosed within another
HTML element in the HTML document, the former will be
represented as a child node of the latter in the DOM diagram.
16.2 Selecting Nodes in DOM
• Nodes in the DOM can be accessed and modified in Javascript.
• In order to access nodes in DOM, we need to use the document
object.
• The document object is a built-in Javascript object that
represents the HTML document.
• It comes with a few useful methods and properties for
accessing and modifying DOM nodes.
16.2 Selecting Nodes in DOM
<html>
<head>
<title>DOM Practice</title>
</head>
<body>
<div id = "first">The first div tag</div>
<div class = "myclass">The second div tag</div>
<div class = "myclass">The third div tag</div>
<script type="text/javascript" src="chap7.js"></script>
</body>
</html>
16.2 Selecting Nodes in DOM
16.2.1 getElementById()
• The first method that we will be using is the
getElementById() method.
• This method allows us to select an element in Javascript using
its id attribute. For instance, the first <div> element has id =
"first".
• To select this element using its id, we write
• document.getElementById("first");
• The getElementById() method simply selects the element
and returns the selected element to the caller
16.2 Selecting Nodes in DOM
16.2.2 textContent and innerHTML
To change the text enclosed within this element, we can use
either the textContent or the innerHTML property.
• The <em> and </em> tags are printed on the webpage instead
of being recognised as HTML code.
• If you want the browser to interpret <em>…</em> as HTML
tags, you need to use the innerHTML property. Change the
line to
firstDiv.innerHTML = "<em>I've changed</em>";
• In other words, the browser now recognizes <em> and </em>
as tags and displays the text in italics.
16.2 Selecting Nodes in DOM
16.2.3 getElementsByClassName()
This method selects all the elements that have a certain class
name.
Hence, the method name is getElementsByClassName (plural)
instead of getElementByClassName (singular).
The elements selected are returned as an array.
var myclassDiv =
document.getElementsByClassName("myclass");
myclassDiv[0].textContent = "MyClass 1";
myclassDiv[1].textContent = "MyClass 2";
16.2 Selecting Nodes in DOM
16.2.4 getElementsByTagName()
This method allows us to select elements using tag names.
Similar to the getElementsByClassName() method above, this
method returns more than one element.
Specifically, it returns all the elements that have a certain tag
name. The elements are returned as an array.
document.getElementsByTagName("div")[0].textContent = "Tag
Name 1";
document.getElementsByTagName("div")[1].textContent = "Tag
Name 2";
document.getElementsByTagName("div")[2].textContent = "Tag
Name 3";