Java Script
Java Script
JavaScript
Dr. Indrajeet Kumar
What is JavaScript?
208
What is JavaScript?
Created by Netscape
Originally called LiveWire then LiveScript
209
1
JavaScript is not Java
210
Why JavaScript?
211
212
2
Hello, World!
213
215
3
The <script>…</script> tag
<script type="text/javascript">
.
.
.
</script>
216
<script type="text/javascript">
<!--
some JavaScript code
//-->
</script>
217
Displaying text
The [Link]() method writes a string of text to the browser
<script type="text/javascript">
<!--
[Link]("<h1>Hello, world!</h1>");
//-->
</script>
218
4
[Link]()
Ends in a semicolon
[Link]("<h1>Hello,world!</h1>");
Enclosed in quotes --
denotes a "string"
219
Comments in JavaScript
Multiple line
Uses /* and */
220
<script type="text/javascript">
<!--
// This is my JavaScript comment
[Link]("<h1>Hello!</h1>");
//-->
</script>
221
5
Multiple Line Comment
Example
<script type="text/javascript">
<!--
/* This is a multiple line comment.
* The star at the beginning of this line is optional.
* So is the star at the beginning of this line.
*/
[Link]("<h1>Hello!</h1>");
//-->
</script>
222
Variables
Variables
In JavaScript, variables
are created using the
keyword var Example:
var x = 10;
var y = 17;
6
Variables
Variables declared
Variables declared using
with let can be
var can be re-declared
Redeclaration updated but not re-
and updated within the
declared within the
same scope.
same scope.
226
It cannot be accessed
It can be accessed It cannot be accessed
without initialization,
without initialization without initialization
as it cannot be
as its default value is otherwise it will give
declared without
“undefined”. ‘referenceError’.
initialization.
These variables are These variables are
hoisted but stay in the hoisted but stays in
These variables are
temporal dead zone the temporal dead
hoisted.
untill the zone until the
initialization. initialization.
227
7
Example
var a = 10
Output
function f()
10 20
{
10
var b = 20
[Link](a, b)
}
f();
[Link](a);
228
function f()
{ Output:
229
Example (let)
let a = 10;
let a = 10; function f() {
if (true) {
function f() let b = 9
{ [Link](b);
}
let b = 9
[Link](b);
[Link](b); }
[Link](a); f()
} [Link](a)
f();
Output Output:
9 9
8
let a = 10 /*behaviour of let variables when they are re-
declared in the different scopes.*/
// It is not allowed
let a = 10 let a = 10
if (true) {
// It is allowed let a = 9
a = 10 [Link](a) // It prints 9
}
[Link](a) // It prints 10
Output
Output:
9
Uncaught SyntaxError: Identifier 'a'
10
has already been declared
[Link](a);
let a = 10;
231
Example (const)
//This code explains the use of the const
//This code tries to change the keyword to declare the JavaScript objects.
value of the const variable.
const a =
const a = 10; {
function f() { prop1: 10,
prop2: 9
a=9 }
[Link](a) // It is allowed
} a.prop1 = 3
232
Data Types
9
Primitive Data Types
Numbers - A number can be either an integer or a
decimal
10
Example: Variables
var x = 4; Ans = x + y;
Ans => 15
var y = 11;
Ans = z + x;
var z = “cat”; Ans => cat4
More Examples
var x = 4; Ans = x + y + z;
Ans => 15cat
var y = 11;
Ans = q + x + y;
var z = “cat”; Ans => 17411
var q = “17”;
OUTPUT Output
2 Hello There
1.3 Single quotes work fine
Infinity can embed Hello There
NaN
239
11
let b1 = true; let age = null;
[Link](b1); [Link](age)
240
Arrays
Creating an Array
12
Accessing Array Elements
Adding Elements
Array Length
13
JavaScript Arrays
An array is a special variable, which can hold
more than one value:
const cars = ["Saab", "Volvo", "BMW"];
Syntax:
const array_name = [item1, item2, ...];
const cars = ["Saab", "Volvo", "BMW"];
Syntax:
cars = ["Saab", "Volvo", "BMW"];
var cars;
246
<html> <body>
<h1>JavaScript Arrays</h1>
<h2>Declaring an Array Using const</h2>
<p id="demo"></p>
<script>
const cars = ["Saab", "Volvo", "BMW"];
{
const cars = ["Toyota", "Volvo", "BMW"];
}
[Link]("demo").innerHTML = cars[0];
</script>
</body>
</html>
247
let x = 42;
//[Link](x);
x = "hello";
//[Link](x);
x = [1, 2, 3];
[Link](x)
Output
42
hello
[ 1, 2, 3 ]
248
14
JavaScript Object Literal
An object literal is a list of
property names:values inside curly
braces {}.
{firstName:"John", lastName:"Doe",
age:50, eyeColor:"blue"};
// Create an Object
const person = {};
249
let obj = {
name: "Sourav",
age: 23,
job: "Developer"
};
[Link](obj);
Output
Output
251
15
Operations on JavaScript Objects
Accessing Object Properties
let obj = { name: "Sourav", age: 23 };
// Using Dot Notation
[Link]([Link]);
// Using Bracket Notation
[Link](obj["age"]);
Output
Sourav
23
252
[Link] = 23;
[Link](obj);
Output
Output
254
16
Removing Properties from an Object:
The delete operator removes properties from an
object.
Output
{ model: 'Tesla' }
255
Output
false
true
256
17
Merging Objects
Objects can be merged using [Link]() or the spread
syntax { …obj1, …obj2 }.
Output
{ name: 'Sourav', age: 23 }
258
Object Length
Output
2
259
18
Variable Names
Operators
+ Addition = = Equality
- Subtraction ! = Inequality
* Multiplication ! Logical NOT
/ Division &&Logical AND
% Modulus || Logical OR
++ Increment ? Conditional
Selection
-- Decrement
Aggregate Assignments
19
Increment and Decrement
Control Structures
The If Statement
20
Repeat Loops
A repeat loop is a group of statements that is repeated
until a specified condition is met.
269
21
The For Loop
The for loop is used when there is
a need to have a counter of some
kind.
The counter is initialized before
the loop starts, tested after each
iteration to see if it is below a
target value, and finally updated
at the end of the loop.
i++updates the
counter at the end
of the loop
<SCRIPT <SCRIPT
LANGUAGE= LANGUAGE=
"JavaScript"> "JavaScript">
[Link]("1");
[Link]("2");
for (i=1; i<=5; i++)
[Link]("3");
[Link](i);
[Link]("4");
[Link]("5");
</SCRIPT>
22
for (let i = 1; i <= 3; i++)
{
[Link]("Count:", i);
}
273
do…while Loop
Syntax: Example:
do { let test = 1;
// Statements do
} {
while(conditions) [Link](test);
test++;
}
while(test<=5)
274
do…while while
It is an exit-controlled It is an entry-controlled
loop loop.
The number of
The number of
iterations will be at
iterations depends upon
least one irrespective
the condition specified
of the condition
The block code is The block of code is
controlled at the end controlled at starting
275
23
"switch" statement
A switch statement can replace multiple if checks.
switch(x) {
case 'value1': // if (x === 'value1')
[break]
case 'value2': // if (x === 'value2')
default:
}
276
let a = 2 + 2;
switch (a)
{
case 3:
alert( 'Too small' );
break;
case 4:
alert( 'Exactly!' );
break;
case 5:
alert( 'Too big' );
break;
default:
alert( "I don't know such values" );
} 277
let a = 2 + 2;
switch (a) {
case 3:
alert( 'Too small' );
case 4:
alert( 'Exactly!' );
case 5:
alert( 'Too big' );
default:
alert( "I don't know such values" );
}
278
24
let a = "1";
let b = 0;
switch (+a) {
case b + 1:
alert("this runs, because +a is 1, exactly equals b+1");
break;
default:
alert("this doesn't run");
}
279
let a = 3;
switch (a) {
case 4:
alert('Right!');
break;
default:
alert('The result is strange. Really.');
}
280
25
Functions
Functions are a collection of JavaScript statement that
performs a specified task.
Functions
The inputs are passed into the function and are known
as arguments or parameters.
Defining Functions
26
Example: Function
Input/Argument: x
z = 3;
sqr_z = square(z); Output: x*x
Example: Function
function sum_of_squares(num1,num2)
{return (num1*num1) + (num2*num2);}
function sum_of_squares(num1,num2)
{return (square(num1) + square(num2));}
function sum(x, y) {
return x + y;
}
[Link](sum(6, 9));
// Function Definition
function welcomeMsg(name)
{
return ("Hello " + name + " welcome to
JavaScript Class");
}
287
27
Arrow Functions
Syntax:
288
Output
Normal way [ 8, 6, 7, 9 ]
Using Arrow Function [ 8, 6, 7, 9 ]
289
(function ()
{
[Link]("This runs immediately!");
}
) ();
290
28
Callback Functions
291
Anonymous Functions
Anonymous functions are functions without a name.
They are often used as arguments to other functions.
setTimeout(function () {
[Link]("Anonymous function executed!");
}, 1000);
292
Nested Functions
Functions defined within other functions are called
nested functions. They have access to the variables of
their parent function.
function outerFun(a) {
function innerFun(b) {
return a + b;
}
return innerFun;
}
const addTen = outerFun(10);
[Link](addTen(5)); 293
29
Pure Functions
Pure functions return the same output for the
same inputs and do not produce side effects. They
do not modify state outside their scope, such as
modifying global variables, changing the state of
objects passed as arguments, or performing I/O
operations.
function pureAdd(a, b)
{
return a + b;
}
[Link](pureAdd(2, 3));
294
function fact(num)
{
if (num == 0) {
return 1;
}
else {
return num * fact( num - 1 );
}
}
296
30
function map(f, a) {
const result = new Array([Link]);
for (let i = 0; i < [Link]; i++) {
result[i] = f(a[i]);
}
return result;
}
const numbers = [0, 1, 2, 5, 10];
const cubedNumbers = map(function (x) {
return x * x * x;
}, numbers);
[Link](cubedNumbers);
297
let myFunc;
if (num === 0) {
myFunc = function (theObject)
{
[Link] = "Toyota";
};
}
function multiply() {
return num1 * num2;
}
[Link](multiply());
298
function getScore() {
const num1 = 2;
const num2 = 3;
function add() {
return `${name} scored ${num1 + num2}`;
}
return add();
}
[Link](getScore());
299
31
function A(x) {
function B(y) {
function C(z) {
[Link](x + y + z);
}
C(3);
}
B(2);
}
A(1);
300
301
302
32
What can a JavaScript Do?
JavaScript gives HTML designers a programming
tool:
simple syntax
JavaScript can put dynamic text into an HTML
page
JavaScript can react to events
JavaScript can read and write HTML elements
JavaScript can be used to validate data
JavaScript can be used to detect the visitor’s
browser
JavaScript can be used to create cookies
Store and retrieve information on the visitor’s
computer
303
JavaScript How To
The HTML <script> tag is used to insert a JavaScript into
an HTML page
<script type=“text/javascript”>
[Link](“Hello World!”)
</script>
Ending statements with a semicolon?
Optional; required when you want to put multiple
statements on a single line
JavaScript can be inserted within the head, the body, or
use external JavaScript file
How to handle older browsers?
<script type=“text/javascript”>
<!—
[Link](“Hello World!”)
// -->
</script>
304
305
33
JavaScript in <head>
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
[Link]("p1").innerHTML = "Paragraph replaced by me";
}
</script>
</head>
<body>
<p id="p1">Paragraph.</p>
</body>
</html>
JavaScript in <body>
<!DOCTYPE html>
<html>
<body>
<p id="p1">Paragraph.</p>
External JavaScript
Scripts can also be placed in external files:
External file: [Link]
function myFunction() {
[Link]("demo").innerHTML =
"Paragraph changed.";
}
34
You can place an external script reference in <head> or <body> as you like.
The script will behave as if it was located exactly where the <script> tag is
located.
External JavaScript Advantages
Placing scripts in external files has some advantages:
It separates HTML and code
It makes HTML and JavaScript easier to read and maintain
Cached JavaScript files can speed up page loads
You can also add several script files to one page - use several script tags:
<script src="[Link]"></script>
<script src="[Link]"></script>
310
311
35
HTML DOM methods are actions you can perform (on
HTML Elements).
HTML DOM properties are values (of HTML Elements)
that you can set or change.
<html> <body>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "Hell
o World!";
</script> </body> </html>
312
313
36
<html> <body>
<h2>JavaScript HTML DOM</h2>
<div id="main">
<p>Finding HTML Elements by Tag Name</p>
<p>This example demonstrates the
<b>getElementsByTagName</b> method.</p>
</div>
<p id="demo"></p>
<script>
const x = [Link]("main");
const y = [Link]("p");
[Link]("demo").innerHTML =
'The first paragraph (index 0) inside "main" is: ' +
y[0].innerHTML;
</script></body></html>
315
<html> <body>
<h2>JavaScript HTML DOM</h2>
<p>Finding HTML Elements by Class Name.</p>
<p class="intro">Hello World!</p>
<p class="intro">This example demonstrates the
<b>getElementsByClassName</b> method.</p>
<p id="demo"></p>
<script>
const x = [Link]("intro");
[Link]("demo").innerHTML =
'The first paragraph (index 0) with class="intro" is: ' +
x[0].innerHTML;
</script> </body> </html>
316
37
Finding HTML Elements by HTML Object
Collections
319
Changing HTML
320
38
<html>
<body>
<h2>JavaScript can Change HTML</h2>
<p id="p1">Hello World!</p>
<script>
[Link]("p1").innerHTML = "New text!";
</script>
<p>The paragraph above was changed by a script.</p>
</body>
</html>
321
<html>
<body>
<script>
[Link]("myImage").src =
"[Link]";
</script>
</body>
</html>
322
<html>
<body>
<script>
[Link]("demo").innerHTML = "Date :
" + Date(); </script>
</body>
</html>
323
39
[Link]()
In JavaScript, [Link]() can be used to write
directly to the HTML output stream:
<html>
<body>
<p>Bla bla bla</p>
<script>
[Link](Date());
</script>
<p>Bla bla bla</p>
</body>
</html>
Never use [Link]() after the
document is loaded. It will overwrite the
document. 324
<html><head><script>
function validateForm() {
let x = [Link]["myForm"]["fname"].value;
if (x == "") {alert("Name must be filled out");
return false;
}}
</script></head>
<body>
<h2>Form Validation</h2>
<form name="myForm" action="/action_page.php"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form></body></html> 325
HTML events:
• When a user clicks the mouse
• When a web page has loaded
• When an image has been loaded
• When the mouse moves over an element
• When an input field is changed
• When an HTML form is submitted
• When a user strokes a key
326
40
<!DOCTYPE html>
<html>
<body>
<script>
function changeText(id) {
[Link] = "Ooops!";
}
</script>
</body>
</html>
327
41