0% found this document useful (0 votes)
3 views

Chapter 4 Java Script

This document provides an overview of JavaScript, a popular scripting language used for creating dynamic and interactive web pages. It covers the differences between Java and JavaScript, the syntax for embedding JavaScript in HTML, and various JavaScript functionalities such as alerts, prompts, and variable declarations. Additionally, it discusses data types, operators, and the use of arrays and objects in JavaScript.

Uploaded by

mikiwendiye92
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter 4 Java Script

This document provides an overview of JavaScript, a popular scripting language used for creating dynamic and interactive web pages. It covers the differences between Java and JavaScript, the syntax for embedding JavaScript in HTML, and various JavaScript functionalities such as alerts, prompts, and variable declarations. Additionally, it discusses data types, operators, and the use of arrays and objects in JavaScript.

Uploaded by

mikiwendiye92
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Web/Internet Programming

Chapter Four

Java Script

1 Prepared by Sudi.M 04/12/2025


JavaScript
The growth of WWW is resulted in demand for
dynamic and interactive web sites.
 Java script is a scripting language produced by
Netscape for use within HTML Web pages.
JavaScript is loosely based on Java and it is built
into all the major modern browsers.
 JavaScript is a scripting language - a scripting
language is a lightweight programming language
It is the most popular scripting language on the
internet.
JavaScript is case-sensitive!

2 Prepared by Sudi.M 04/12/2025


Are Java and JavaScript the
same?
 NO! Java and JavaScript are two

completely different languages!


 Java (developed by Sun Microsystems) is a

powerful and very complex programming


language - in the same category as C and C+
+.

3 Prepared by Sudi.M 04/12/2025


JavaScript…
JavaScript is used
 to improve user interface
 to create pop-up window and alerts
 to Interact with the user
 to create dynamic pages
 to validate forms
 to detect browsers (reacting to user
actions on Browser)
 A JavaScript can be used to validate
form data before it is submitted to a
server, this will save the server from
extra processing.
 to create cookies, and much more.
4 Prepared by Sudi.M 04/12/2025
JavaScript…
 A JavaScript consists of JavaScript statements
that are placed within the <script>... </script>
HTML tags in a web page.
The <script> tag tells the browser program to
begin interpreting all the text between these
tags as a script.
JavaScript statements ends with
semicolon.
The syntax of your JavaScript will be as follows
<script ...>
JavaScript code
</script>
5 Prepared by Sudi.M 04/12/2025
JavaScript…
 The script tag takes three important attributes:
 src: specify the location of the external script.
 language: specifies what scripting language you are
using.
Typically, its value will be “javascript”.
 type: used to indicate the scripting language in use.
Its value should be set to "text/javascript".
 Type and language has similar function we use
language to specify the language used in the script.
 So your JavaScript segment will looks like:
<script language="javascript" type="text/javascript">
JavaScript code
</script>

6 Prepared by Sudi.M 04/12/2025


Placing JavaScript in an HTML file
Scripts in the head section: Scripts to
be executed when they are called, or when
an event is triggered, must be placed in
the head section.
<html>
<head>
<script type="text/JavaScript">....
</script>
</head>

7 Prepared by Sudi.M 04/12/2025


Placing JavaScript in an HTML
file
 Scripts in the body section: Scripts to be executed
when the page loads must be placed in the body
section.
 When you place a script in the body section it
generates the content of the page.
<html>
<head>
</head>
<body>
<script type="text/JavaScript">
....
</script>
</body>
</html>
 You can also have scripts in both the body and the
head section.
8 Prepared by Sudi.M 04/12/2025
Using an External JavaScript
Sometimes you might want to run the same
JavaScript on several pages, without having to write
the same script on every page.
To simplify this, you can write a JavaScript in an
external file.
Save the external JavaScript file with .js file
extension.
Note: The external script cannot contain the
<script> tag!
To use the external script, write the JS file in the
"src" attribute of the <script> tag:
Note: Remember to place the script exactly
where you want to write the script!
9 Prepared by Sudi.M 04/12/2025
 With traditional programming languages, like
Ending Statements With a Semicolon?

C++ and Java, each code statement has to end


with a semicolon.
 Many programmers continue this habit when

writing JavaScript, but in general, semicolons


are optional!
 However, semicolons are required if

you want to put more than one


statement on a single line
10 Prepared by Sudi.M 04/12/2025
A Simple Java 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>
11 Prepared by Sudi.M 04/12/2025
Comment
To explain what the script does
Two types of comment
Comment on single line(//)
Comment on multiple line(/*…..*/)

12 Prepared by Sudi.M 04/12/2025


Using the alert() Method
<head>
<script language=“JavaScript”>
alert(“An alert triggered by JavaScript”);
</script>
</head>
It is the easiest methods to use amongst
alert(), prompt() and confirm().
You can use it to display textual information
to the user
The user can simply click “OK” to close it.

13 Prepared by Sudi.M 04/12/2025


Using the confirm() Method
<head>
<script language=“JavaScript”>
confirm(“Are you happy with the class?”);
</script>
</head>
This box is used to give the user a choice
either OK or Cancel.
You can also put your message in the
method.

14 Prepared by Sudi.M 04/12/2025


Using the alert() Method
<head>
<script language=“JavaScript”>
prompt(“What is your student id number?”);
prompt(“What is your name?”,”No name”);
</script>
</head>
This is the only one that allows the user to
type in his own response to the specific
question.
You can give a default value to avoid
displaying “undefined”.

15 Prepared by Sudi.M 04/12/2025


Three methods
<script language="JavaScript">
alert("This is an Alert method");
confirm("Are you OK?");
prompt("What is your name?");
prompt("How old are you?","20");
</script>

16 Prepared by Sudi.M 04/12/2025


JavaScript Variables
A variable is a "container" for information
you want to store.
Variable names are case sensitive
They must begin with a letter, underscore
character or dollar symbol
It includes uppercase and lowercase letters,
digits from 0 through 9 , underscore and
dollar sign
No space and punctuation characters
You should not use any of the JavaScript
reserved keyword as variable name.
17 Prepared by Sudi.M 04/12/2025
JavaScript Variables…
You can create a variable with the var
statement:
var strname = some value

You can also create a variable without the


var statement:
strname = some value
Assign a Value to a Variable
var strname = "Hege"

strname = "Hege“
18 Prepared by Sudi.M 04/12/2025
Which one is legal?
 My_variable
 $my_variable
legal
 1my_example
 _my_variable
 @my_variable
 My_variable_example
 ++my_variable
 %my_variable Illegal
 #my_variable
 ~my_variable
 myVariableExample

19 Prepared by Sudi.M 04/12/2025


The scope of a variable
 The scope of a variable is the region of your
program in which it is defined.
 JavaScript variable will have only two scopes.
 Global Variables: A global variable has global
scope which means it is defined everywhere in
your JavaScript code.
 Local Variables: A local variable will be
visible only within a function where it is
defined.
Function parameters are always local to that
function.

20 Prepared by Sudi.M 04/12/2025


Data Types
 JavaScript allows the same variable to contain
different types of data values.
 Primitive data types
Number: integer & floating-point numbers
Boolean: logical values “true” or “false”
String: a sequence of alphanumeric characters
 Composite data types (or Complex data types)
Object: a named collection of data
Array: a sequence of values
 Special data types
Null: as initial value is assigned
Undefined: the variable has been created but not yet
assigned a value
21 Prepared by Sudi.M 04/12/2025
Numeric Data Types
It is an important part of any
programming language for doing
arithmetic calculations.
JavaScript supports:
Integers: A positive or negative
number with no decimal places.
Ranged from –253 to 253
Floating-point numbers: usually
written in exponential notation.
3.1415…, 2.0e11

22 Prepared by Sudi.M 04/12/2025


Integer and Floating-point number example
<script language=“JavaScript”>
var integerVar = 100;
var floatingPointVar = 3.0e10;
// floating-point number 30000000000
document.write(integerVar);
document.write(floatingPointVar);
</script>

The integer 100 and the number


30,000,000,000 will be appeared in the
browser window.
23 Prepared by Sudi.M 04/12/2025
Boolean Values
A Boolean value is a logical value of either
true or false. (yes/no, on/off)
Often used in decision making and data
comparison.
In JavaScript, you can use the words “true”
and “false” to indicate Boolean values.
True=1
False=0

24 Prepared by Sudi.M 04/12/2025


Boolean value example
<head>
<script language=“JavaScript”>
var result;
result = (true*10 + false*7);
alert(“true*10 + false*7 =“ , result);
</script>
</head>

The expression is converted to


(1*10 + 0*7) = 10

25 Prepared by Sudi.M 04/12/2025


Strings
<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>

 A string variable can store a sequence of alphanumeric


characters, spaces and special characters.
 String can also be enclosed in single quotation marks (‘) or
in double quotation marks (“).
 What is the data type of “100”?
 String but not number type

26 Prepared by Sudi.M 04/12/2025


What is an Object?
An object is a thing, anything, just as things
in the real world.
E.g. (cars, dogs, money, books, … )
In the web browser, objects are the browser
window itself, forms, buttons, text boxes, …
Methods are things that objects can do.
Cars can move, dogs can bark.
Window object can alert the user “message()”.
All objects have properties.
Cars have wheels, dogs have legs.
Browser has a name and version number.

27 Prepared by Sudi.M 04/12/2025


Array
An Array contains a set of data represented
by a single variable name.
Arrays in JavaScript are represented by the
Array Object, we need to “new Array()”
to construct this object.
The first element of the array is “Array[0]”
until the last one Array[n-1].
E.g. myArray = new Array(5)
We have myArray[0,1,2,3,4].

28 Prepared by Sudi.M 04/12/2025


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>
You can also declare arrays with variable
length.
arrayName = new Array();

29 Prepared by Sudi.M 04/12/2025


Null & Undefined
An “undefined” value is returned
when you attempt to use a variable
that has not been defined or
you have declared but you forgot to
provide with a value.
Null refers to “nothing”
You can declare and define a variable
as “null” if you want absolutely
nothing in it, but you just don’t want
it to be “undefined”.
30 Prepared by Sudi.M 04/12/2025
Null & Undefined example
<html>
<head>
<title> Null and Undefined example </title>
<script language=“JavaScript”>
var test1, test2 = null;
alert(“No value assigned to the variable” +
test1);
alert(“A null value was assigned” + test2);
</script>
</head>
<body> … </body>
</html>
31 Prepared by Sudi.M 04/12/2025
Expressions
It is a set of literals, variables, operators
that are merged and evaluated to a single
value.
Left operand operator right operand
By using different operators, you can create
the following expressions.
Arithmetic,
logical
String and
conditional expressions.

32 Prepared by Sudi.M 04/12/2025


Operators
 Arithmetic operators
Logical operators
Comparison operators
String operators
Bit-wise operators
Assignment operators
Conditional operators

33 Prepared by Sudi.M 04/12/2025


Arithmetic operators
left operand operator right operand

Operator Name Description Example


+ Addition Adds the operands 3+5
- Subtraction Subtracts the right 5-3
operand from the
left operand
* Multiplicati Multiplies the 3*5
on operands
/ Division Divides the left 30 / 5
operand by the right
operand
% Modulus Calculates the 20 % 5
remainder

34 Prepared by Sudi.M 04/12/2025


Unary Arithmetic Operators
Binary operators take two operands.
Unary type operators take only one
operand.
Which one add value first, and then assign
Name Example
value to the variable?
Post Incrementing operator Counter++
(postfix)
Post Decrementing operator Counter--

Pre Incrementing operator (prefix) ++counter

Pre Decrementing operator --counter

35 Prepared by Sudi.M 04/12/2025


Logical operators
Used to perform Boolean operations on
Boolean operands
Operator Name Description Example
&& Logical Evaluate to 3>2 && 5<2
and “true” when both
operands are
true
|| Logical or Evaluate to “true 3>1 || 2>5
when either
operand is true

! Logical Evaluate to 5 != 3
not “true” when the
operand is false

36 Prepared by Sudi.M 04/12/2025


Comparison operators
Used to compare two numerical values
Operat Name Description Example
or
== Equal Perform type conversion “5” == 5
before checking the equality
=== Strictly equal No type conversion before “5” ===
testing 5
!= Not equal “true” when both operands 4 != 2
are not equal
!== Strictly not No type conversion before 5 !==
equal testing nonequality “5”
> Greater than “true” if left operand is 2>5
greater than right operand
< Less than “true” if left operand is less 3<5
than right operand
>= Greater than or “true” if left operand is 5 >= 2
equal greater than or equal to the
37 Prepared by Sudi.M right operand 04/12/2025
<= Less than or “true” if left operand is less 5 <= 2
Strict Equality Operators
<script language=“JavaScript”>
var currentWord=“75”;
var currentValue=75;
var outcome1=(currentWord == currentValue);
var outcome2=(currentWord === currentValue);
alert(“outcome1: “ + outcome1 + “ : outcome2: “
+ outcome2);
</script>
Surprised that outcome1 is True, outcome2 is
False
JavaScript tries very hard to resolve numeric
and string differences.
38 Prepared by Sudi.M 04/12/2025
String operator
JavaScript only supports one string
operator for joining two strings.
Operator Name Description Return
value
+ String Joins two “HelloWorld”
concatenatio strings
n
<script language=“JavaScript”>
var myString = “ ”;
myString = “Hello” + “World”;
alert(myString);
</script>

39 Prepared by Sudi.M 04/12/2025


Bit Manipulation operators
Perform operations on the bit
representation of a value, such as shift left
or right.
Operat Name Description
or
& Bitwise AND Examines each bit position
| Bitwise OR If either bit of the operands
is 1, the result will be 1
^ Bitwise XOR Set the result bit 1, only if
either bit is 1, but not both
<< Bitwise left shift Shifts the bits of an
expression to the left
>> Bitwise signed Shifts the bits to the right,
right shift and maintains the sign
>>> Bitwise zero-fill Shifts the bits of an
40 Prepared by Sudi.M 04/12/2025
right shift expression to right
Assignment operators
Used to assign values to variables
Operator Description Example
= Assigns the value of the right A=2
operand to the left operand
+= Add the operands and assigns the A += 5
result to the left operand
-= Subtracts the operands and A -= 5
assigns the result to the left
operand
*= Multiplies the operands and A *= 5
assigns the result to the left
operand
/= Divides the left operands by the A /= 5
right operand and assigns the
result to the left operand
%= Assigns the remainder to the left A %= 2
41
operand
Prepared by Sudi.M 04/12/2025
The most common problem
<script language=“JavaScript”>
if (alpha = beta) { … }
if (alpha == beta) { … }
</script>
Don’t mix the comparison operator
and the assignment operator.
double equal sign (==) and the equal
operator (=)

42 Prepared by Sudi.M 04/12/2025


Order of Precedence
Precedence Operator
1 Parentheses, function calls
2 , ~, -, ++, --, new, void, delete
3 *, /, %
4 +, -
5 <<, >>, >>>
6 <, <=, >, >=
7 ==, !=, ===, !==
8 &
9 ^
10 |
11 &&
12 ||
13 ?:
14 =, +=, -=, *=, …
15 The comma (,) operator

43 Prepared by Sudi.M 04/12/2025


Precedence Example

Value = (19 % 4) / 1 – 1 - !false


Value = 3 / 1 – 1 - !false
Value = 3 / 1 – 1 - true
Value = 3 – 1 - true
Value = 3–2
Value = 1

44 Prepared by Sudi.M 04/12/2025


 Example of variable, data types
<html><head><title> Billing System of Web Shoppe </title></head><body>
<h1 align="center"> Billing System of Web Shoppe </h1>
<script language="JavaScript">
firstCustomer = new Array();
billDetails = new Array(firstCustomer);
var custName, custDob, custAddress, custCity, custPhone;
var custAmount, custAmountPaid, custBalAmount;
custName=prompt("Enter the first customer's name:", "");
custDob=prompt("Enter the first customer's date of birth:", "");
custAddress=prompt("Enter the first customer's address:", "");
custPhone=prompt("Enter the first customer's phone number:", "");
custAmount=prompt("Enter the total bill amount of the first customer:", "");
custAmountPaid=prompt("Enter the amount paid by the first customer:", "");
custBalAmount = custAmount - custAmountPaid;
firstCustomer[0]=custName;
firstCustomer[1]=custDob;
firstCustomer[2]=custAddress;
firstCustomer[3]=custPhone;
firstCustomer[4]=custBalAmount;
document.write("<B>" + "You have entered the following details for first
customer:" + "<BR>");
document.write("Name: " + billDetails[0][0] + "<BR>");
document.write("Date of Birth: " + billDetails[0][1] + "<BR>");
document.write("Address: " + billDetails[0][2] + "<BR>");
document.write("Phone: " + billDetails[0][3] + "<BR>");
(custBalAmount == 0) ? document.write("Amount Outstanding: " +
custBalAmount):document.write("No amount due")
</script></body></html>
45 Prepared by Sudi.M 04/12/2025
Conditional Statement
“if” statement
“if … else” statement
“else if” statement
“if/if … else” statement
“switch” statement

46 Prepared by Sudi.M 04/12/2025


“if” statement
if (condition)
{
statements;
}
It is the main conditional statement in
JavaScript.
The keyword “if” always appears in
lowercase.
The condition yields a logical true or false
value.
The condition is true, statements are
47 executed.
Prepared by Sudi.M 04/12/2025
“if” statement example
<script language=“JavaScript”>
var chr = “ ”;

if (chr == ‘A’ || chr == ‘O’) {
document.write(“Vowel variable”);
}
</script>

48 Prepared by Sudi.M 04/12/2025


“if … else” statement
if (condition)
{
statements;
}
else
{
statements;
}
You can include an “else” clause in an if
statement when you want to execute some
statements if the condition is false.
49 Prepared by Sudi.M 04/12/2025
Ternary Shortcut (concise)
<script language=“JavaScript”>
If (3 > 2) {
alert(“True”);
}
else {
alert(“False”);
}
(3 > 2) ? alert(“True”) : alert(“False”);
</script>
Substitute for a simple “if/else” statement.

50 Prepared by Sudi.M 04/12/2025


“else if” statement
if (condition) {
statement;
}
else if (condition) {
statement;
}
else {
statement;
}
Allows you to test for multiple expression for
one true value and executes a particular block
of code.
51 Prepared by Sudi.M 04/12/2025
“if/if…else” statement example
<script language=“JavaScript”>
var chr;
chr = prompt(“Please enter a character : “,””);
if (chr >= ‘A’)
{
if (chr <= ‘Z’)
alert(“Uppercase”);
else if (chr >= ‘a’)
{
alert(“Lowercase”);
}
}
</script>
52 Prepared by Sudi.M 04/12/2025
“switch” statement
switch (expression)
{
case label1:
statements;
break;
default:
statements;
}
Allows you to merge several evaluation tests
of the same variable into a single block of
statements.
53 Prepared by Sudi.M 04/12/2025
“switch” statement example
<script language=“JavaScript”>
var chr;
chr = prompt(“Pls enter a character in lowercase:”,””);
switch(chr){
case ‘a’ :
alert(“Vowel a”); break;
case ‘e’ :
alert(“Vowel e”); break;
default :
alert(“Not a vowel”);
}
</script>

54 Prepared by Sudi.M 04/12/2025


Looping Statement
“for” Loops
“for/in” Loops
“while” Loops
“do … while” Loops

55 Prepared by Sudi.M 04/12/2025


“for” statement
for (initial_expression; test_exp; change_exp)
{
statements;
}
One of the most used and familiar loops is the
for loop.
It iterates through a sequence of statements for
a number of times controlled by a condition.
The change_exp determines how much has been
added or subtracted from the counter variable.

56 Prepared by Sudi.M 04/12/2025


“for” statement example
<script language=“JavaScript”>
var counter;
for (counter = 1; counter <= 10;
counter++)
{
document.write(counter*counter + “ “);
}
</script>
Display the square of numbers
Output: 1 4 9 16 25 36 49 64 81 100

57 Prepared by Sudi.M 04/12/2025


“for/in” statement
for (counter_variable in object)
{
statements;
}
When the for/in statement is used, the counter
and termination are determined by the length
of the object.
The statement begins with 0 as the initial value
of the counter variable, terminates with all the
properties of the objects have been executed.
E.g. array - no more elements found

58 Prepared by Sudi.M 04/12/2025


“for/in” statement example
<script language=“JavaScript”>
var book;
var booklist = new Array(“Chinese”,
“English”, “Jap”);
for (var counter in booklist) {
book += booklist[counter] + “ “;
}
alert(book);
</script>

59 Prepared by Sudi.M 04/12/2025


“while” statement
initial value declaration;
while (condition)
{
statements;
increment/decrement statement;
}
The while loop begins with a termination
condition and keeps looping until the
termination condition is met.
The counter variable is managed by the
context of the statements inside the curly
braces.
60 Prepared by Sudi.M 04/12/2025
“While” statement example
<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>

61 Prepared by Sudi.M 04/12/2025


“do … while” statement
do
{
statements;
counter increment/decrement;
}
while (termination condition)
The do/while loop always executes
statements in the loop in the first iteration of
the loop.
The termination condition is placed at the
bottom of the loop.
62 Prepared by Sudi.M 04/12/2025
Gaalatomaa

63 Prepared by Sudi.M 04/12/2025

You might also like