Académique Documents
Professionnel Documents
Culture Documents
JavaScript
Web Programming
i.e the client side script code is sent from the server to the
client.
JavaScript
Is a client-side scripting language (lightweight
programming language)
An interpreted language
Web Programming
JavaScript Capabilities
Improve the user interface of a website
Make your site easier to navigate
Easily create pop-up alert, windows
Replace images on a page without reload the page
Form validation (Validate user input)
Put dynamic text in an HTML page
React to events (interactive)
Read and write HTML elements in an HTML page
Web Programming
JavaScript confusion
JavaScript
Java
Web Programming
JavaScript (contd)
How to add JavaScript to an HTML page
anywhere in the HTML document
<body>
<script type=text/javascript>
document.write(hello);
</script>
</body>
Web Programming
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>
Web Programming
JavaScript (contd)
<script type=text/javascript>
javascript code (functions)
</script>
or
<script type=text/javascript src=js_file.js></script>
</head>
Web Programming
10
11
JavaScript
<html>
<!-- Dave Reed
js01.html
2/01/04 -->
<head>
<title>JavaScript Page</title>
</head>
<body>
<script type="text/javascript">
// silly code to demonstrate output
document.write("Hello world!");
document.write("<p>How are <br />" +
"<i>you</i>?</p>");
</script>
<p>Here is some static text as well.
</p>
</body>
</html>
12
13
Web Programming
14
Web Programming
15
js05.html
2/01/04 -->
<head>
<title>Interactive page</title>
</head>
<body>
<script type="text/javascript">
userName = prompt("What is your name?", "");
userAge = prompt("Your age?", "");
userAge = parseFloat(userAge);
document.write("Hello " + userName + ".")
if (userAge < 18) {
document.write(" Do your parents know " +
"you are online?");
}
</script>
<p>The rest of the page...
</body>
</html>
JavaScript (contd)
If more than one statement per line, separate them using (;)
Comments
// single line comment
/* multi line
comment */
17
Web Programming
JavaScript (contd)
Literals (constants)
12 // The number twelve
1.2 // The number one point two
"hello world" // A string of text
'Hi' // Another string
true // A Boolean value
false // The other Boolean value
null // Absence of an object
18
Web Programming
JavaScript (contd)
Identifiers
19
Web Programming
JavaScript (contd)
Reserved words
break do if switch typeof case else in this var catch
false instanceof tHRow void continue finally new
true while default for null try with delete function
return
20
Web Programming
JavaScript (contd)
21
Web Programming
Data Types
22
Web Programming
23
3.1415, 2.0e11
Web Programming
24
25
(1*10 + 0*7) = 10
Variables
26
Web Programming
Legal
Illegal
Web Programming
Strings
28
Web Programming
Strings example
<head>
<script language=JavaScript>
document.write(This is a string.);
document.write(This string contains quote.);
var myString = My testing string;
alert(myString);
</script>
</head>
29
What is an Object?
30
Array
31
We have myArray[0,1,2,3,4].
Web Programming
Array Example
<script language=JavaScript>
Car = new Array(3);
Car[0] = Ford;
Car[1] = Toyota;
Car[2] = Honda;
document.write(Car[0] + <br>);
document.write(Car[1] + <br>);
document.write(Car[2] + <br>);
</script>
32
Variable
Declaration
syntax:
var identifier [ = initial_value ]
ex. var x;
var first_name = Abebe;
33
Web Programming
<head>
<script language=JavaScript>
Variable declaration
var id;
id = prompt(What is your student id number?);
alert(id);
name = prompt(What is your name?,No name);
alert(name);
</script>
</head>
34
35
Web Programming
36
Web Programming
37
\b
\f
\t
\n
\r
\\
\
\
Meaning
Backspace
Form feed
Horizontal tab
New line
Carriage return
Backslash
Single quote
Double quote
Web Programming
Expressions
38
Arithmetic, logical
String and conditional expressions.
Web Programming
Operators
Arithmetic operators
Logical operators
Comparison operators
String operators
Bit-wise operators
Assignment operators
Conditional operators
39
Web Programming
Operators
Arithmetic Operators
Operator
+
Description
Addition
Subtraction
Multiplication
Division
++
Increment
--
Decrement
40
Example
x=2
y=2
x+y
x=5
y=2
x-y
x=5
y=4
x*y
15/5
5/2
5%2
10%8
10%2
x=5
x++
x=5
x--
Web Programming
Result
4
20
3
2.5
1
2
0
x=6
x=4
Assignment operators
Used to assign values to variables
Operator
Description
Example
A=2
+=
A += 5
-=
A -= 5
*=
A *= 5
/=
A /= 5
%=
41
A %= 2
Comparison operators
Used to compare two numerical values
Operator
Name
Description
Example
==
Equal
5 == 5
===
Strictly equal
!=
Not equal
!==
Strictly not
equal
>
Greater than
<
Less than
>=
Greater than or
equal
5 >= 2
<=
Less than or
equal
5 <= 2
42
5 === 5
4 != 2
5 !== 5
2>5
3<5
Web Programming
Logical operators
Operator
&&
||
!
43
Name
Description
Web Programming
Example
3>2 &&
5<2
3>1 ||
2>5
5 != 3
<script language=JavaScript>
var currentWord=75;
var currentValue=75;
var outcome1=(currentWord == currentValue);
var outcome2=(currentWord === currentValue);
alert(outcome1: + outcome1 + : outcome2: + outcome2);
</script>
44
String operator
Operator
Name
Description
Return value
String
concatenation
HelloWorld
<script language=JavaScript>
var myString = ;
myString = Hello + World;
alert(myString);
</script>
45
Web Programming
JavaScript (contd)
Conditional statements
if, if else
switch
conditional operator
46
Web Programming
if statement
if (condition) { statements; }
47
Web Programming
if statement example
<script language=JavaScript>
var chr = ;
if (chr == A || chr == O) {
document.write(Vowel variable);
}
</script>
|| operator - increase the speed of the script
48
Web Programming
if else statement
if (condition) { statements; }
else { statements; }
49
Web Programming
else if statement
if (condition) { statement; }
else if (condition) { statement; }
else { statement; }
51
Web Programming
switch statement
switch (expression) {
case label1:
statements; break;
default:
statements;
}
52
Web Programming
Looping Statement
for Loops
for/in Loops
while Loops
do while Loops
break statement
continue statement
54
Web Programming
for statement
for (initial_expression; test_exp; change_exp)
{ statements; }
55
56
for/in statement
for (counter_variable in object)
{ statements; }
57
E.g. array
for(varaible in object)
{
code to be executed
}
Note: The code in the body of the for...in loop is executed once
for each property
58
Web Programming
59
Web Programming
while statement
initial value declaration;
while (condition) {
statements;
increment/decrement statement;
}
60
61
<html>
<head>
<title>While loop example</title>
<script language=JavaScript>
var counter = 100;
var numberlist = ;
while (counter > 0) {
numberlist += Number + counter + <br>;
counter -= 10;
}
document.write(numberlist);
</script> <body> </body>
</html>
Web Programming
do while statement
do {
statements;
counter increment/decrement;
} while (termination condition)
62
Web Programming
JavaScript (contd)
Functions
Web Programming
Example:
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()" />
</form>
</body>
</html>
64
Web Programming
User-defined functions
function definitions are similar to C++/Java, except:
no return type for the function (since variables are loosely typed)
no types for parameters (since variables are loosely typed)
by-value parameter passing only (parameter gets copy of argument)
function isPrime(n)
// Assumes: n > 0
can limit variable scope
// Returns: true if n is prime, else false
{
if the first use of a variable is preceded
if (n < 2) {
return false;
with var, then that variable is local to
}
the function
else if (n == 2) {
return true;
}
for modularity, should make all
else {
variables in a function local
for (var i = 2; i <= Math.sqrt(n); i++)
{
if (n % i == 0) {
return false;
}
}
return true;
} 65
Web Programming
}
The return statement is used to specify the value that is returned from the function
<html>
<head>
<script type="text/javascript">
function product(a,b)
{
return a*b;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(product(4,3));
</script>
</body>
</html
66
Web Programming
Javascript Objects
67
Web Programming
68
Web Programming
69
Web Programming
JavaScript Numbers
JavaScript numbers can be written with, or without decimals:
Example:
var pi=3.14; // Written with decimals
var x=34;
// Written without decimals
Extra large or extra small numbers can be written with scientific (exponent) notation:
Example:
var y=123e5; // 12300000
var z=123e-5; // 0.00123
All JavaScript Numbers are 64-bit
JavaScript is not a typed language. Unlike many other programming languages, it does not
define different types of numbers, like integers, short, long, floating-point etc.
All numbers in JavaScript are stored as 64-bit (8-bytes) base 10, floating point numbers.
70
Web Programming
71
Web Programming
A string can be any text inside quotes.You can use simple or double quotes:
Syntax
var txt = new String(string);
or more simply:
var txt = string;
Example
var carname="Volvo XC60";
You can access each character in a string with its position (index):
Example
var character=carname[7];
String indexes are zero-based, which means the first character is [0], the second is [1], and so on.
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
Example
var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
72
Web Programming
String Length
The length of a string (a string object) is found in the built in property
length:
Example
var txt="Hello World!";
document.write(txt.length);
The indexOf() method returns the position (as a number) of the first found
occurrence of a specified text inside a string:
Example
var str="Hello world, welcome to the universe.";
var n=str.indexOf("welcome");
73
Web Programming
<!DOCTYPE html>
<html>
<body>
<p id="p1">Click the button to locate where "locate" first occurs.</p>
<p id="p2">0</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str=document.getElementById("p1").innerHTML;
var n=str.indexOf("locate");
//20
document.getElementById("p2").innerHTML=n+1;
}
</script>
</body>
</html>
74
Web Programming
Matching Content
The match() method can be used to search for a matching content in a string
<!DOCTYPE html>
<html>
<body>
<script>
var str="Hello world!";
document.write(str.match("world") + "<br>"); // world
document.write(str.match("World") + "<br>"); //Null
document.write(str.match("world!")); // world!
</script>
</body>
</html>
75
Web Programming