Javascript
Javascript
Javascript
1
THE THREE LAYERS OF THE
WEB
HTML for Content
<p class=“warning”>There is no <em>download
link</em> on this page.</p>
3
Why use client-side programming?
PHP 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
4
Why use client-side programming?
5
What is Javascript?
6
What is Javascript?
7
Javascript vs Java
8
Javascript vs Java
+ =
9
Advantages of javascript
1. Easy to use and learn
2. An interpreted language
3. Used to create interactive websites
4. Embedded within HTML
5. Quick development
6. Used to add dynamic functionality to websites
7. Validate the user input
8. Event-driven
9. Platform independence
10. Easy debugging and testing
10
Limitations of javascript
11
Syntax of Javascript
<html>
<body>
<script type=“text/javascript”>
-----------------------------------
</script>
</body>
</html>
12
Write output to a Page
<html>
<body>
<script type=“text/javascript”>
document.write(“hello world”)
</script>
</body>
</html>
13
Different Places where Javascript can be Placed
14
Using JavaScript in your HTML
15
A Simple Script
<html>
<head><title>First JavaScript Page</title></head>
<body>
<h1>First JavaScript Page</h1>
<script type="text/javascript">
document.write("<hr>");
document.write("Hello World Wide Web");
document.write("<hr>");
</script>
</body>
</html>
16
Embedding JavaScript
<html>
<head><title>First JavaScript Program</title></head>
<body>
<script type="text/javascript"
src="your_source_file.js"></script>
</body>
Inside your_source_file.js
</html>
document.write("<hr>");
document.write("Hello World Wide Web");
document.write("<hr>");
18
Hiding JavaScript from Incompatible Browsers
<script type="text/javascript">
<!–
document.writeln("Hello, WWW");
// -->
</script>
<noscript>
Your browser does not support JavaScript.
</noscript>
19
alert(), confirm(), and prompt()
<script type="text/javascript">
alert("This is an Alert method");
confirm("Are you OK?");
prompt("What is your name?");
prompt("How old are you?","20");
</script>
20
alert() and confirm()
alert("Text to be displayed");
Display a message in a dialog box.
The dialog box will block the browser.
21
prompt()
23
JavaScript Variables
Example
var x = 5;
var y = 6;
var z = x + y;
24
JavaScript Identifiers
25
JavaScript is untyped language. This means that a JavaScript
variable can hold a value of any data type. Unlike many other
languages, you don't have to tell JavaScript during variable
declaration what type of value the variable will hold. The
value type of a variable can change during the execution of a
program and JavaScript takes care of it automatically.
26
JavaScript Variable Scope
27
EXAMPLE
<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
</body>
</html>
28
JavaScript Reserved Words
29
What is an Operator?
30
JavaScript Arithmetic Operators
31
• Exponentiation
• The exponentiation operator (**) raises the first operand to the
power of the second operand.
• Example
• let x = 5; Ans =25
• let z = x ** 2;
x ** y produces the same result as Math.pow(x,y):
• Example
• let x = 5;
• let z = Math.pow(x,2);
32
• Incrementing
• The increment operator (++) increments Ans =6
numbers.
• Example
• let x = 5;
• x++;
• let z = x;
• Decrementing
• The decrement operator (--) decrements
numbers.
• Example
• let x = 5;
• x--;
• let z = x;
Ans =4
33
JavaScript Assignment Operators
34
JavaScript String Operators
35
• The += assignment operator can also be used to add (concatenate)
strings:
• Example
• var txt1 = "What a very ";
• txt1 += "nice day";
• The result of txt1 will be:
36
JavaScript Comparison Operators
37
JavaScript Logical Operators
38
Conditional (Ternary) Operator
• Syntax
• variablename = (condition) ? value1:value2
• Example
• let voteable = (age < 18) ? "Too young":"Old enough";
39
JavaScript Type Operators
40
JavaScript Comments
41
Multi-line Comments
42
JavaScript If-else
• The JavaScript if-else statement is used to execute the code whether 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
43
JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if
statement is given below.
1. if(expression){
2. //content to be evaluated
3. }
Let’s see the simple example of if statement in javascript.
• 1. <script>
• 2. var a=20;
• 3. if(a>10){
• 4. document.write("value of a is greater than 10");
• 5. }
• 6. </script>
44
JavaScript If...else Statement
It evaluates the content whether condition is true of false. The syntax of 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
• }
45
• 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>
• Output of the above
46
JavaScript If...else if statement
• It evaluates the content only if expression is true from several expressions. The
signature of JavaScript if else if statement is given below.
• if(expression1){
• //content to be evaluated if expression1 is true
• }
• else if(expression2){
• //content to be evaluated if expression2 is true
• }
• else if(expression3){
• //content to be evaluated if expression3 is true
• }
• else{
• //content to be evaluated if no expression is true
• }
47
• Let’s see the simple example of if else if statement in javascript.
• <script>
• var a=20;
• if(a==10){
• document.write("a is equal to 10");
• }
• else if(a==15){
• document.write("a is equal to 15");
• }
• else if(a==20){
• document.write("a is equal to 20");
• }
• else{
• document.write("a is not equal to 10, 15 or 20");
• }
• </script>
48
JavaScript Switch
• The JavaScript switch statement is used to execute one code from multiple expressions. It is just like
else if statement that we have learned in previous page. But it is convenient than if..else..if because it
can be used with numbers, characters etc.
• The signature of JavaScript switch statement is given below.
• switch(expression){
• case value1:
• code to be executed;
• break;
• case value2:
• code to be executed;
• break;
• ......
• default:
• code to be executed if above values are not matched;
• }
49
Let’s see the simple example of switch statement in javascript.
<script>
var grade='B';
var result;
switch(grade){
case 'A’:
result="A Grade";
break;
case 'B':
result="B Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
50
Loops in JavaScript
• Looping in programming languages is a feature which facilitates the execution of
a set of instructions/functions repeatedly while some condition evaluates to true.
For example, suppose we want to print “Hello World” 10 times. This can be done
in two ways as shown below:
• Iterative Method
• Using Loops
51
• Iterative Method
• Iterative method to do this is to write the document.write() statement 10 times. <script
type = "text/javascript">
• document.write("Hello World\n");
• document.write("Hello World\n");
• document.write("Hello World\n");
• document.write("Hello World\n");
• document.write("Hello World\n");
• document.write("Hello World\n");
• document.write("Hello World\n");
• document.write("Hello World\n");
• document.write("Hello World\n");
• document.write("Hello World\n");
• < /script>
52
• Using Loops
• In Loop, the statement needs to be written only once and the loop will be
executed 10 times as shown below:
• <script type = "text/javascript">
• var i;
• for (i = 0; i < 10; i++)
• {
• document.write("Hello World!\n");
• }
• < /script>
53
• In computer programming, a loop is a sequence of instructions that is repeated
until a certain condition is reached.
• An operation is done, such as getting an item of data and changing it, and then
some condition is checked such as whether a counter has reached a prescribed
number.
• Counter not Reached: If the counter has not reached the desired number, the
next instruction in the sequence returns to the first instruction in the sequence and
repeat it.
• Counter reached: If the condition has been reached, the next instruction “falls
through” to the next sequential instruction or branches outside the loop.
54
• There are mainly two types of loops:
• 1. Entry Controlled loops: In this type of loops the test condition is tested before
entering the loop body. For Loop and While Loop are entry controlled loops.
• 2. Exit Controlled Loops: In this type of loops the test condition is tested or
evaluated at the end of loop body. Therefore, the loop body will execute atleast
once, irrespective of whether the test condition is true or false. do – while loop is
exit controlled loop.
55
While Loop
• 1. while loop: A while loop is a control flow statement that allows code to be
executed repeatedly based on a given Boolean condition. The while loop can be
thought of as a repeating if statement.
• Syntax :
• while (boolean condition)
• {
• loop statements...
• }
56
While Loop
• While loop starts with the checking of condition. If it evaluated to true, then the
loop body statements are executed otherwise first statement following the loop is
executed. For this reason it is also called Entry control loop
• Once the condition is evaluated to true, the statements in the loop body are
executed. Normally the statements contain an update value for the variable being
processed for the next iteration.
• When the condition becomes false, the loop terminates which marks the end of
its life cycle.
57
Example
58
FOR LOOP
• for loop: for loop provides a concise way of writing the loop structure. Unlike a
while loop, a for statement consumes the initialization, condition and
increment/decrement in one line thereby providing a shorter, easy to debug
structure of looping. Syntax: for (initialization condition; testing condition;
• 2. increment/decrement)
• 3. {
• 4. statement(s)
• 5. }
59
• Initialization condition: Here, we initialize the variable in use. It marks the start
of a for loop. An already declared variable can be used or a variable can be
declared, local to loop only.
• 2. Testing Condition: It is used for testing the exit condition for a loop. It must
return a boolean value. It is also an Entry Control Loop as the condition is
checked prior to the execution of the loop statements.
• 3. Statement execution: Once the condition is evaluated to true, the statements in
the loop body are executed.
• 4. Increment/ Decrement: It is used for updating the variable for next iteration.
• 5. Loop termination:When the condition becomes false, the loop terminates
marking the end of its life cycle.
60
EXAMPLE FOR LOOP
61
for…in loop
• JavaScript also includes another version of for loop also known as the for..in
Loops. The for..in loop provides a simpler way to iterate through the properties of
an object. This will be more clear after leaning objects in JavaScript. But this loop
is seen to be very useful while working with objects.
• Syntax:
• for (variableName in Object)
• {
• statement(s)
• }
• In each iteration, one of the properties of Object is assigned to the variable named
variableName and this loop continues until all of the properties of the Object are
processed. Lets take an example to demonstrate how for..in loop can be used to
simplify the work.
62
• <script type = "text/javaScript">
• // JavaScript program to illustrate for..in loop
• // creating an Object
• var languages = { first : "C", second : "Java",
• third : "Python", fourth : "PHP",
• fifth : "JavaScript" };
• // iterate through every property of the
• // object languages and print all of them
• // using for..in loops
• for (itr in languages)
• {
• document.write(languages[itr] + "<br >");
• }
• < /script>
63
DO-WHILE
• do while: do while loop is similar to while loop with only difference that it
checks for condition after executing the statements, and therefore is an example
of Exit Control Loop. Syntax:
• do
• {
• statements..
• }
• while (condition);
64
• 1. do while loop starts with the execution of the statement(s). There is no
checking of any condition for the first time.
• 2. After the execution of the statements, and update of the variable value, the
condition is checked for true or false value. If it is evaluated to true, next iteration
of loop starts.
• 3. When the condition becomes false, the loop terminates which marks the end of
its life cycle.
• 4. It is important to note that the do-while loop will execute its statements atleast
once before any condition is checked, and therefore is an example of exit control
loop.
65
• <script type = "text/javaScript">
• // JavaScript program to illustrate do-while loop
• var x = 21;
• do
• {
• // The line while be printer even
• // if the condition is false
• document.write("Value of x:" + x + "<br />");
• x++;
• } while (x < 20);
• < /script>
• Output:
• Value of x: 21
66
ARRAYS
67
• Initialization of an Array Example (for Method 1): // Initializing while declaring
• var house = ["1BHK", "2BHK", "3BHK", "4BHK"];
• // Initializing after declaring
• house[0] = "1BHK";
• house[0] = "2BHK";
• house[0] = "3BHK";
• house[0] = "4BHK";
• Example (for Method 2): // Initializing while declaring
• // Creates an array having elements 10, 20, 30, 40, 50
• var house = new Array(10, 20, 30, 40, 50);
• //Creates an array of 5 undefined elements
• var house1 = new Array(5);
• //Creates an array with element 1BHK
• var home = new Array("!BHK");
• As shown in above example the house contains 5 elements i.e. (10 , 20, 30, 40, 50) while
house1 contains 5 undefined elements instead of having a single element 5. Hence, while
working with numbers this method is generally not preferred but it works fine with
Strings and Boolean as shown in the example above home contains a single element
1BHK.
68
• An array in JavaScript can hold different elements We can store Numbers,
Strings and Boolean in a single array. Example: Storing number, boolean, strings
in an Array
• var house = ["1BHK", 25000, "2BHK", 50000, "Rent", true];
69
• Accessing Array Elements Array in JavaScript are indexed from 0 so we can
access array elements as follows: var house = ["1BHK", 25000, "2BHK", 50000,
"Rent", true];
alert(house[0]+" cost= "+house[1]);
• var cost_1BHK = house[1];
• var is_for_rent = house[5];
alert("Cost of 1BHK = "+ cost_1BHK);
alert("Is house for rent = ")+ is_for_rent);
70
• Length property of an Array Length property of an Array returns the length of
an Array. Length of an Array is always one more than the highest index of an
Array. Example below illustrates the length property of an Array:
• var house = ["1BHK", 25000, "2BHK", 50000, "Rent", true];
• //len conatains the length of the array
• var len = house.length;
• for (var i = 0; i < len; i++)
• alert(house[i]);
71
JavaScript Functions
72
JavaScript Function Syntax
73
Function Invocation
74
Function Return
75
Linking to a JavaScript file: script
76
Event-driven programming
77
Event-driven programming
78
Buttons
<button>Click me!</button> HTML
79
JavaScript functions
function name() {
statement ;
statement ;
...
statement ;
} JS
function myFunction() {
alert("Hello!");
alert("How are you?");
} JS
81
Events
Event handlers are created as attributes added to the HTML tags in
which the event is triggered.
An Event handler adopts the event name and appends the word
“on” in front of it.
85
PROPERTIES OF AN OBJECT
Property Value
firstName John
lastName Doe
Age 50
eyeColor blue
86
Object Methods
87
Creating a JavaScript Object
88
BY OBJECT LITERAL
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
89
2) By creating instance of Object
90
3) By using an Object constructor
Here, you need to create function with arguments. Each argument value
can be assigned in the current object by using this keyword.
The this keyword refers to the current object.
The example of creating object by object constructor is given below.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
91
Defining method in JavaScript Object
92
Data Validation
121
• JavaScript Form Validation
• HTML form validation can be done by JavaScript.
• If a form field (fname) is empty, this function alerts a
message, and returns false, to prevent the form from
being submitted:
122
Example
script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="abc.jsp" onsubmit="return validatefor
m()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form> 123