Javascript
Javascript
Course : Javascript
Introduction to Javascript
⚫ This means that web page developer need not have any other software
other than a text editor to develop any web page.
2
Course : Javascript
3
C
S Client Side Scripting
3
8
0
Course : Javascript
Why we Use JavaScript?
⚫ Using HTML we can only design a web page but you can
not run any logic on web browser like addition of two
numbers, check any condition, looping statements (for,
while), decision making statement (if-else) at client side.
4
Course : Javascript
Where it is used?
⚫ Client-side validation
5
Course : Javascript
6
C
S Why use client-side programming?
3
8
0
server-side programming (JSP) benefits:
security: has access to server's private data; client
can't see source code
compatibility: not subject to browser compatibility
issues
power: can write files, open connections to servers,
connect to databases, ...
Course : Javascript
7
C
S Why use client-side programming?
3
8
0
JSP already allows us to create dynamic web
pages. Why also use client-side scripting?
client-side scripting (JavaScript) benefits:
usability: can modify a page without having to post
back to the server (faster UI)
efficiency: can make small, quick changes to page
without waiting for server
event-driven: can respond to user actions like clicks
and key presses
Course : Javascript
8
C
S What is Javascript?
3
8
0 a lightweight programming language ("scripting
language")
• used to make web pages interactive
• insert dynamic text into HTML (ex: user name)
• react to events (ex: page load user click)
• get information about a user's computer (ex: browser
type)
• perform calculations on user's computer (ex: form
validation)
• A web standard (but not supported identically by all
browsers)
NOT related to Java other than by name and some
syntactic similarities
Course : Javascript
9
C
S Javascript vs Java
3
8
0
•interpreted, not compiled
•more relaxed syntax and rules
• fewer and "looser" data types
• variables don't need to be declared
• errors often silent (few exceptions)
•key construct is the function rather than the
class.
•Functions are used in many situations
•contained within a web page and integrates
with its HTML/CSS content
Course : Javascript
1
0
C
S Javascript vs Java
3
8
0
+ =
Course : Javascript
1
1
C
S Event-driven programming
3
8
0
12
Course : Javascript
Uses of JavaScript
⚫ Client-side validation
⚫ Validate user input in an HTML form before sending the data to a server.
⚫ Manipulate HTML "layers" including hiding, moving, and allowing the user
to drag them around a browser window.
⚫ Displaying popup windows and dialog boxes (like alert dialog box, confirm
dialog box and prompt dialog box)
13
Course : Javascript
Limitations of JavaScript
14
Course : Javascript
History
15
Course : Javascript
Writing JavaScript code
<script ...>
JavaScript code
</script>
16
Course : Javascript
JavaScript code inside body tag
<!DOCTYPE html>
<html>
<body>
</body>
</html>
17
Course : Javascript
JavaScript code inside head tag
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML =
"Paragraph changed.";
}
</script>
<head>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try
it</button>
</body>
</html>
18
Course : Javascript
External JavaScript file
19
Course : Javascript
External JavaScript file
⚫ Example
<script src="myScript.js"></script>
20
Course : Javascript
Course : Javascript
Comment
22
Course : Javascript
Variable
23
Course : Javascript
Variable
let message;
message = 'Hello'; // store the string
24
Course : Javascript
Variable
25
Course : Javascript
How variable works?
let message = “Hello”
26
Course : Javascript
Difference between let and var :
28
Course : Javascript
Local variables
⚫ For example:
<script>
function abc() {
let x=10; //local variable
}
</script>
or
<script>
if(10<13) {
let y=20;//javascript local variable
}
</script>
29
Course : Javascript
Global variable
⚫ For example:
<script>
var value=10;//global variable
function a() {
alert(value);
}
function b() {
alert(value);
}
</script>
30
Course : Javascript
Declaring global through window object
⚫ For example:
window.value=20;
function m() {
window.value=200; //declaring global variable by window object
}
function n() {
alert(window.value); //accessing global variable from other function
}
31
Course : Javascript
Rules to declare a variable
32
Course : Javascript
Constants
⚫ Example
const myBirthday = '18.04.1982';
myBirthday = '01.01.2001'; // error, can't reassign the constant!
33
Course : Javascript
Constants
let n = 123;
n = 12.345;
35
Course : Javascript
Data types - Number
alert( 1 / 0 ); // Infinity
36
Course : Javascript
Data types - Number
⚫ Example
37
Course : Javascript
Data types - String
⚫ Example
38
Course : Javascript
Data types - Boolean
⚫ The boolean type has only two values: true and false
39
Course : Javascript
Data types – “null” value
⚫ The special null value does not belong to any of the types.
40
Course : Javascript
Data types – “undefined” value
let x;
alert(x); // shows "undefined"
let x = 123;
x = undefined;
alert(x); // "undefined"
41
Course : Javascript
typeof
42
Course : Javascript
typeof
typeof 0 // "number"
43
Course : Javascript
Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Remainder)
++ Increment
-- Decrement
44
Course : Javascript
Assignment Operators
45
Course : Javascript
Comparison Operators
Given that x = 5
== equal to x == 8 false
x == 5 true
x == "5" true
=== equal value and equal type x === 5 true
x === "5" false
!= not equal x != 8 true
!== not equal value or not equal type x !== 5 false
x !== "5" true
x !== 8 true
> greater than x>8 false
< less than x<8 true
>= greater than or equal to x >= 8 false
46
Course : Javascript
Logical Operators
|| or (x == 5 || y == 5) is false
47
Course : Javascript
Conditional Operator
• Syntax
• Example
48
Course : Javascript
Comparing different types
Case Value
2 < 12 true
2 == "John" false
49
Course : Javascript
Output statement
50
Course : Javascript
Using innerHTML
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
51
Course : Javascript
Using document.write()
document.write("Hello World!");
52
Course : Javascript
Using window.alert()
• The alert box takes the focus away from the current window,
and forces the browser to read the message.
53
Course : Javascript
Using console.log()
• console.log(5 + 6);
• console.log(5 + 6);
54
Course : Javascript
Conditional statement
55
Course : Javascript
Conditional statement - if
if (condition) {
// block of code to be executed if the
condition is true
}
Example
if (hour < 18) {
greeting = "Good day";
}
56
Course : Javascript
Conditional statement – else
if (condition) {
// block of code to be executed if the
condition is true
} else {
// block of code to be executed if the
condition is false
}
57
Course : Javascript
Conditional statement – else
Example
58
Course : Javascript
Conditional statement – if .. else .. if
if (condition1) {
// block of code to be executed if
condition1 is true
} else if (condition2) {
// block of code to be executed if the
condition1 is false and condition2 is true
} else {
// block of code to be executed if the
condition1 is false and condition2 is false
}
59
Course : Javascript
Conditional statement – if .. else .. if
Example
60
Course : Javascript
Conditional statement – switch
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
61
Course : Javascript
Conditional statement – switch
Example
switch (grade) {
case 'A': msg = "Good job”;
break;
case 'B': msg = "Pretty good";
break;
case 'C': msg = "Passed";
break;
case 'D': msg = "Not so good";
break;
case 'F': msg = "Failed";
break;
default: msg = "Unknown grade";
}
62
Course : Javascript
Conditional statement – switch
63
Course : Javascript
Conditional statement – switch
while (condition) {
// code block to be executed
}
65
Course : Javascript
Loop statements – while
66
Course : Javascript
Loop statements – do..while
do {
// code block to be executed
}while (condition);
67
Course : Javascript
Loop statements – do..while
i=1;
do {
console.log(i);
i++;
}while (i <= 10);
68
Course : Javascript
Loop statements – for
69
Course : Javascript
Loop statements – for
71
Course : Javascript
Array
• Syntax:
var array_name = [item1, item2, ...];
• Example
var cars = ["Saab", "Volvo", "BMW"];
72
Course : Javascript
Array
➢ Example
var cars = [
"Saab",
"Volvo",
"BMW"
];
➢ Example
var cars = new Array("Saab", "Volvo", "BMW");
73
Course : Javascript
Accessing elements of Array
• Example
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
74
Course : Javascript
Accessing elements of Array
75
Course : Javascript
Cycling array elements using for loop
77
Course : Javascript
length property
• Length actually does not give the count of values in the array,
but the greatest numeric index plus one example :
let fruits = [];
fruits[123] = "Apple";
alert( fruits.length ); // 124
78
Course : Javascript
Array object methods
• Push
Append the element to the end of the array:
fruits.push("Pear");
• Pop
Extracts the last element of the array and returns it:
79
Course : Javascript
Array object methods
• shift
Extracts the first element of the array and returns it:
• unshift
Add the element to the beginning of the array:
fruits.unshift('Apple');
fruits.push("Orange", "Peach");
fruits.unshift("Pineapple", "Lemon");
81
Course : Javascript
Other Array object methods
• Deleteing element
var fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0]; // Changes the first element in fruits to undefined
The concat() method does not change the existing arrays. It always
returns a new array.
82
Course : Javascript
Splice method
83
Course : Javascript
Splice method
arr.slice([start], [end])
85
Course : Javascript
Iterate: forEach
86
Course : Javascript
Iterate: forEach
function display(item,index,arr){
console.log(`Value in index ${index} is ${item}`)
}
87
Course : Javascript
Searching in array
• arr.indexOf(item, from)
➢ – looks for item starting from index from, and returns the index where it
was found, otherwise -1.
• arr.lastIndexOf(item, from)
➢ – same, but looks for from right to left.
• arr.includes(item, from)
➢ – looks for item starting from index from, returns true if found.
88
Course : Javascript
Searching in array
• Examples :
alert( arr.indexOf(0) ); // 1
alert( arr.indexOf(false) ); // 2
alert( arr.indexOf(null) ); // -1
89
Course : Javascript
find and findIndex methods
• Syntax :
• The function is called for elements of the array, one after another:
➢ item is the element.
➢ index is its index.
➢ array is the array itself.
• Syntax :
• The function is called for elements of the array, one after another:
➢ item is the element.
➢ index is its index.
➢ array is the array itself.
• Example
let users = [
{id: 1, name: "John"},
{id: 2, name: "Pete"},
{id: 3, name: "Mary"}
];
alert(user.name); // John
92
Course : Javascript
Filter methods
• The find method looks for a single (first) element that makes
the function return true whereas if there may be many
occurances, we can use arr.filter(fn).
93
Course : Javascript
Filter methods
• Example:
let users = [
{id: 1, name: "John"},
{id: 2, name: "Pete"},
{id: 3, name: "Mary"}
];
alert(someUsers.length); // 2
94
Course : Javascript
map methods
• The arr.map method calls the function for each element of the
array and returns the array of results.
95
Course : Javascript
sort method
• The sort method sorts the array in place, changing its element
order.
let arr = [ 1, 2, 15 ];
// the method reorders the content of arr
arr.sort();
console.log( arr ); // 1, 15, 2
96
Course : Javascript
sort method
function compareNumeric(a, b) {
if (a > b) return 1;
if (a == b) return 0;
if (a < b) return -1;
}
let arr = [ 1, 2, 15 ];
arr.sort(compareNumeric);
console.log(arr); // 1, 2, 15
97
Course : Javascript
sort method
arr.sort((v1,v2)=>{
if(v1.Name > v2.Name) return 1;
else if(v1.Name == v2.Name) return 0;
else return -1;
});
98
Course : Javascript
split method
• Example 2 :
//If delimiter is empty then it would split the string
into an array of letters:
let str = "test";
alert( str.split('') ); // t,e,s,t
99
Course : Javascript
split method
100
Course : Javascript
join method
For instance:
101
Course : Javascript
Map
102
Course : Javascript
Map
• Example
let map = new Map();
console.log( map.size ); // 3
103
Course : Javascript
Iteration over Map
104
Course : Javascript
Iteration over Map
⚫ Example
function product(p1, p2) {
return p1 * p2; // The function returns the product of p1 and p2
}
106
Course : Javascript
Function
107
Course : Javascript
Function - Local variables
For example:
function showMessage() {
let message = "Hello, I'm JavaScript!"; // local variable
alert( message );
}
108
Course : Javascript
Function – Outer variables
109
Course : Javascript
Function – Outer variables
showMessage();
alert( userName ); // John, unchanged, the function did not access the outer variable
110
Course : Javascript
Function – Parameter
111
Course : Javascript
Function – Default Parameter
function multiply(a, b = 1) {
return a * b;
}
console.log(multiply(5, 2));
// expected output: 10
console.log(multiply(5));
// expected output: 5
112
Course : Javascript
Function – Returning a value
function sum(a, b) {
return a + b;
}
113
Course : Javascript
Function expressions
Arrow function
117
Course : Javascript
Multi-line Arrow Functions
let sum = (a, b) => { // the curly brace opens a multiline function
let result = a + b;
return result; // if we use curly braces, then we need an explicit "return"
};
alert( sum(1, 2) ); // 3
Course : Javascript
Callback Functions
120
Course : Javascript
Callback Functions
121
Course : Javascript
Synchronous and Asynchronous code
122
Course : Javascript
Synchronous code
console.log('Before');
console.log('Reading user details from database');
sleepFor(3000);
console.log('User details read');
console.log('After');
console.log('Before');
console.log('Reading user details from database');
setTimeout(()=>{
console.log('User details read');
},2000);
console.log('After');
124
Course : Javascript
Asynchronous code
console.log('Before');
let user = getUser(1);
console.log("User : "+user);
console.log('After');
function getUser(id) {
setTimeout(() => {
console.log('Reading user details....');
return({id:1001,name:'Amit'});
},2000);
}
125
Course : Javascript
Asynchronous code
console.log('Before');
getUser(1,(user)=> {
console.log("User : ",user);
});
console.log('After');
function getUser(id,callback) {
setTimeout(() => {
console.log('Reading user details....');
callback({id:1001,name:'Amit'});
},2000);
}
126
Course : Javascript
Promise
127
Course : Javascript
Objects
128
Course : Javascript
Creating Objects
1) By object literal
129
Course : Javascript
Creating Object by object literal
⚫ Syntax:
object={property1:value1,property2:value2.....propertyN:valueN}
⚫ Example
emp={id:102,name:"Shyam Kumar",salary:40000}
console.log(emp.id+" "+emp.name+" "+emp.salary);
130
Course : Javascript
Creating Object by instance of Object
⚫ Syntax:
var objectname=new Object();
Here, new keyword is used to create object.
⚫ Example:
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
console.log(emp.id+" "+emp.name+" "+emp.salary);
131
Course : Javascript
Creating Object by Object constructor
132
Course : Javascript
Adding, modifying, removing and accessing property
let user = {
name: “Kiran",
age: 30
};
• Adding new property to user
• user.branch = “CS”;
• Modifying property
• user.name = “Kiran Kumar”;
• Deleting the property from user
• delete user.name
• Accessing property
• console.log(user.name);
• console.log(user[“name”]
133
Course : Javascript
Reading a non-existing property just returns undefined.
In operator
• Syntax :
• "key" in object
• Example
• let user = { name: "John", age: 30 };
• alert( "age" in user ); // true, user.age exists
• alert( "blabla" in user ); // false, user.blabla doesn't exist
134
Course : Javascript
For..in loop
• Syntax:
for (key in object) {
// executes the body for each key among object properties
}
• Example:
let user = { for (let key in user) {
name: "John", // keys
age: 30, alert( key ); // name, age, isAdmin
isAdmin: true // values for the keys
}; alert( user[key] ); // John, 30, true
}
135
Course : Javascript
Object referencing
• For primitive data type data’s are copied from one variable to
another variable
• For instance:
let message = "Hello!";
let phrase = message;
136
Course : Javascript
Copying object
137
Course : Javascript
Comparing by reference
139
Course : Javascript
Object methods
let user = {
name: "John",
age: 30
};
user.sayHi = function() {
alert("Hello!");
};
user.sayHi(); // Hello!
140
Course : Javascript
Method shorthand
• Object methods can access the information stored in the object using
this reference.
let user = {
name: "John",
age: 30,
sayHi() {
// "this" is the "current object"
alert(this.name);
}
};
user.sayHi(); // John
142
Course : Javascript
“this” in methods
let user = {
name: "John",
age: 30,
sayHi() {
alert(user.name); // "user" instead of "this"
}
};
143
Course : Javascript