You are on page 1of 50

Lesson objective

• After this lesson, you will be able to:


♠ Define JavaScript variables.
♠ Create JavaScript statements.
♠ Create function declarations.
♠ Create function expressions.
♠ Convert objects to a different type.
♠ Write conditional statements.
♠ Write looping statements.
♠ Handle errors.
Compiled By Aliazar D. (MSc in SEng) 2
JavaScript History and Versions

• JavaScript was introduced as part of the


Netscape 2.0 browser
• Microsoft soon released its own version called
JScript
• (European Computer Manufacture Association)
ECMA developed a standard language known
as ECMAScript
• ECMAScript Edition 3 is widely supported and
is what we call it now “JavaScript”

Compiled By Aliazar D. (MSc in SEng) 3


What is JavaScript
• JavaScript is a lightweight, interpreted programming language.
• JavaScript is used in millions of Web pages, to improve the design, validate forms,
detect browsers, create cookies, and much more.
• JavaScript is the most popular scripting language on the internet, and works in all
major browsers, such as Chrome, Internet Explorer, Mozilla, Firefox, Netscape,
and Opera.
• JavaScript is not Java. They are similar in some ways but fundamentally different
in others.
• JavaScript enables shopping carts, form validation, calculations, special graphic
and text effects, image swapping, image mapping, clocks, and more.
• Usually JavaScript code is embedded within HTML code using the script tag.
4
Compiled By Aliazar D. (MSc in SEng)
Conti..
• Advantages of JavaScript
⁕ Less server interaction: You can validate user input
before sending the page off to the server.
⁕ Immediate feedback to the visitors: They don't
have to wait for a page reload to see if they have
forgotten to enter something.
⁕ Increased interactivity: You can create interfaces
that react when the user hovers over them with a
mouse or activates them via the keyboard.
⁕ Interpreted language, not compiled
• Designed to be embedded in browsers
⁕ Ideal for adding interactivity to HTML pages
⁕ Detect browser versions
⁕ Work with info from user via HTML forms
⁕ Create cookies
⁕ Validate form data
⁕ Read and write HTML elements
• It’s free, no license required
Compiled By Aliazar D. (MSc in SEng) 5
Conti..
• HelloWorld in JavaScript
<html>
<head>
<title>JavaScript HelloWorld!</title>
</head>

<body>
<script language="JavaScript">

document.write('Javascript says "Hello World!"')

</script>
</body>

</html>
Compiled By Aliazar D. (MSc in SEng) 6
Conti..
<html>
• JavaScript can be located in the head, <head>
body or external file <script src="xxx.js"></script>
◙ Head section or
• Ensures script is loaded before <script type="text/javascript">
trigger event ....
◙ Body section </script>
• Script executes when body loads </head>
◙ External <body>
• Allows scripts to run on several <script type="text/javascript">
pages ....
</script>
</body>
Compiled By Aliazar D. (MSc in SEng) 7
Conti..
<html>
<head>
<script type="text/javascript">
function sayHello()
{
alert("Hello World")
}
</script>
</head>

<body>
<script type="text/javascript">

document.write("Hello World")

</script>
<br>
<input type="button" onclick="sayHello()" value="Say Hello"/>
</body>
</html>

Compiled By Aliazar D. (MSc in SEng) 8


Identifier
• Identifier is a name given
to a program element JavaScript Keywords
• Syntax rules for names
(identifiers):
⁂ Must begin with letter
or underscore ( _ )
⁂ Must contain only
letters, underscores,
and digits (or certain
other characters)
⁂ Must not be a
reserved word
⁂ Case Sensitive!!
Compiled By Aliazar D. (MSc in SEng) 9
Variables and Data Types

• Type of a variable is dynamic: depends on the type of data it


contains
• JavaScript has six data types:
⁜ Number
⁜ String
⁜ Boolean (values true and false)
⁜ Object
⁜ Null (only value of this type is null)
⁜ Undefined (value of newly created variable)
Compiled By Aliazar D. (MSc in SEng) 10
Variables
• Must declare variables before they’re used in the program
⁕ Declare at the top of the program & terminate each statement with ‘;’
⁕ Initialize variables when appropriate
⁕ Local variables (declared within a function) destroyed after function
exit
• Can only be accessed within the function
Syntax:
var id [= expression];
• Example – Assignments
var x= 2.50;
var taxRate = .075;
var y;

Compiled By Aliazar D. (MSc in SEng) 11


JavaScript Operators

• Operators are used to create compound expressions from


simpler expressions
• Operators can be classified according to the number of
operands involved:
– Unary: one operand (e.g., typeof i)
• Prefix or Postfix (e.g., ++i or i++ )
– Binary: two operands (e.g., x + y)
– Ternary: three operands (conditional operator)
Compiled By Aliazar D. (MSc in SEng) 12
JavaScript Operators
• Precedence (high to low) of operators

13
Compiled By Aliazar D. (MSc in SEng)
Example
<html>
<head>
<title>JavaScript HelloWorld!</title>
</head>
<script language='JavaScript'>
var x = 3;
var y = 10;
document.write(typeof x + "<br/>") ;
document.write(x++ * ++y + y +x + "<br/>") ; //(3*11)+11+4
x = 3;
y = 10;
document.write(++x * ++y + y /x + y + "<br/>") ; //(4*11)+(11/4)+(10)
x = 3;
y = 10;
document.write( ++x * y++ + y +x + "<br/>" ) ;//4*10+11+4
document.write ( "y = " + y + " x = " + x );
</script>
Compiled By Aliazar D. (MSc in SEng) 14
</body>
JavaScript Operators:
Automatic Type Conversion

• Binary operators: +, -, *, /, % convert both operands to Number


† Exception: If one of operands of + is String then the other is
converted to String
• Relational operators: <, >, <=, >= convert both operands to Number
† Exception: If both operands are String, no conversion is performed
• Operators ==, != convert both operands to Number
† Exception: If both operands are String, no conversion is performed
• Unary +, - convert their operand to Number
• Logical &&, ||, ! convert their operands to Boolean

Compiled By Aliazar D. (MSc in SEng) 15


Conditional Statements--if

if (some Boolean expression is true)


{
execute the statements within the curly
braces,
otherwise skip to the first statement after the
closing brace
}
Resume execution here in either case

Compiled By Aliazar D. (MSc in SEng) 16


Conditional Statements– if/else

if (some Boolean expression is true)


{
execute these statements, otherwise skip
to ‘else’ clause
}
else {
execute these statements if Boolean
expression is false
}
Resume execution here in either case

Compiled By Aliazar D. (MSc in SEng) 17


Conditional Test Program

• Diagnostic messages indicate in the flow of control


<html>
<head><title>JavaScript</title></head>
<body>
<script laguage="JavaScript">
var variable1 = 1; var variable2 = 2;
if(variable1 >= 0){
document.write("<p> 1 is greater than 0 </p>");
}

document.write("<p>Resuming execution after 'if' statement</p>");


if(variable1 > variable2){
document.write("<p>1 is greater than 2</p>");
}
else {
document.write("<p>2 is greater than 1</p>");
}
document.write("<p> Resuming execution after 'if/else' statement</p>");
</script>
</body> Compiled By Aliazar D. (MSc in SEng) 18
</html>
Switch Case statement
❖ A switch statement which handles exactly this situation, and it does so more efficiently than
repeated if...else if statements.
❖ The interpreter checks each case against the value of the expression until a match is found.
❖ If nothing matches, a default condition will be used.
❖ Syntax:
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
Compiled By Aliazar D. (MSc in SEng) 19
Switch example
<html>
<script type="text/javascript">
var x = window.prompt(" enter a
no. less than 2");
x= Number(x)
switch (x)
{
case 0: document.write("zero")
; break ;
case 1: document.write("one")
; break ;
default: document.write("not
valid")
}
</script>
</html>

Compiled By Aliazar D. (MSc in SEng) 20


Strings

• Strings are sequences of keyboard characters enclosed in single or


double quotes
“Hello World” or ‘Hello World’

• Variables can hold strings


var greeting = “Hello World”

• String can be empty, i.e., contain no characters


var myAnswer = “”

• Use ‘\’ (escape symbol) to ‘type’ prohibited characters


– \b for backspace, \n for newline, \t for tab, \” for double quote

Compiled By Aliazar D. (MSc in SEng) 21


JavaScript
The Arrays Object
❖ The Array object let's you store multiple values in a single variable.
❖ A collection of identical data objects, which are stored in consecutive memory locations under a
common heading or a variable name.
Properties of arrays
✓ Arrays are zero-bounded; that is the index of the first element in the array is 0 and the last element is N-
1, where N is the size of the array.
✓ It is illegal to refer to an element outside of the array bounds, and your program will crash or have
unexpected results.
✓ Array can only hold values of one type
❑ Type of array
1. One dimension array
1.1 Enumerated arrays:- Use number as a index.
Example:
var EnumeratedArray= [];
EnumeratedArray[1] = 'This is an enumerated array';
Compiled By Aliazar D. (MSc in SEng) 22
Conti..
1.2 Associative array: uses a string instead of a number as an index.
Example:
var associativeArray= [];
associativeArray ['person'] = 'John Smith';
2. Two dimension array: has more than one dimension is called multi-
dimension array.
var stuff = [[1, 2, 3],['one', 'two', 'three’],
['apple', 'orange', 'banana']];
alert (stuff [2][1]);

Compiled By Aliazar D. (MSc in SEng) 23


How do you create an Array object?

❑ You can create an array in 1 of 3 ways:


1) Using new Array()
var colors = new Array ();
colors [0] = "green";
colors[1] = "red";
2) Using new Array (item0, item1, item2 ...)
var colors = new Array("green", "red")
3) Using the literal array approach
This is the shortest way of creating and populating an array, and it's the most
widely used approach. create like this
var colors = ["green", "red"];

Compiled By Aliazar D. (MSc in SEng) 24


How do I access data inside the Array object?

▪ Arrays are great to store several values using only 1 variable.


//"green" is at index position 0, "red" is at index position 1,
etc.
<html>
<body>
<script type="text/javascript">
var colors = ["green","red","yellow","orange","blue"];
var red = colors [1];
document.write (red);
</script>
</body>
</html>
Compiled By Aliazar D. (MSc in SEng) 25
Access all items in the array with a loop:

• Here's how you would access all values inside an array by looping over each of them:
<html>
<body>
<script type="text/javascript">
var colors = ["green","red","yellow","orange","blue"];
for (var i=0;i< colors.length;i++)
{
document.write(colors[i]+"<br />");
}
</script>
</body>
</html>
26
❖ Once you access a value inside an array you can simply retrieve it, as you did in
the previous example, or you can modify it, as follows:
var colors = ["green", "red", "yellow", "orange", "blue"];
colors[2] = "pink";
❖ Now you've replaced the item at index position 2, the third item called "yellow”,
with "pink“
document.write(colors);
❖ The code should print: green, red, pink, orange, blue ("pink" has replaced
"yellow")

27
Working with Program Loops

• A program loop is a set of instructions that is executed


repeatedly
⁕ Use program loops to configure a group of commands to be
executed a set number of times
⁕ The loop uses a counter to track the number of times the command
block has been run

Compiled By Aliazar D. (MSc in SEng) 28


Conti..
<table border = 2
width="100%">
<tr>
<script type =
"text/javascript">
for (num = 1; num <= 4; num++)
{
document.write("<td>" + num
+ "</td>");
}
</script>
</tr>
</table>
Compiled By Aliazar D. (MSc in SEng) 29
Conti..
<table border = 2 width="100%">
<script type = "text/javascript">
for (num = 1; num <= 4; num ++){
document.write("<tr>");
for (J = 1; J <= 4; J ++){
document.write("<td>" + num +
“-” + J + "</td>");
}
document.write("</tr>");
}
</script>
</table>
Compiled By Aliazar D. (MSc in SEng) 30
Conti..
<table border = 2>
<tr>
<script type = "text/javascript">
num = 1;
while(num <= 4)
{
document.write("<td>" + num + "</td>");

num ++;
}
</script>
</tr>
</table>

Compiled By Aliazar D. (MSc in SEng) 31


Conti..
<html>
<table border = 2 width="100%">
<script type = "text/javascript">
num = 1;
while(num <= 4){
document.write("<tr>");
J = 1;
while(J <= 4){
document.write("<td>" + num +
J + "</td>");
J ++;
}
document.write("</tr>");
num ++;
}
</script>
</table>
</html>
Compiled By Aliazar D. (MSc in SEng) 32
JavaScript Functions

❖ A function is a group of reusable code which can be called


anywhere in your programme.
❖ This eliminates the need of writing same code again and
again.
❖ You can divide your big programme in a number of small
and manageable functions.
❖ Like any other advance programming language, JavaScript
also supports all the features necessary to write modular
code using functions. 33
Conti..
• Abstraction • Reasons to use functions
† Functions allows to reduce the size of ⁕ Facilitate communication
program ⁕ Problem simplification
† It allows writing functionality once, then ⁕ Code readability
reuse it ⁕ Reusability
• Encapsulation ⁕ Maintainability
† Functions encapsulate a specific • In JavaScript, functions are the
capability or feature primary encapsulation
† Function name allows us to access a mechanism
function in our program
• Parameterization
† A function may accept parameter 34
Compiled By Aliazar D. (MSc in SEng)
Conti..

⁕ Function Definition • JavaScript function syntax


✓ Before we use a function we
need to define that function. function fname (argument_1, ... ,
The most common way to argument_n)
define a function in JavaScript {
statement_1;
is by using the function statement_2;
keyword, followed by a ...
unique function name, a list statement_m;
of parameters (that might be return return_value;
empty), and a statement block }
surrounded by curly braces.
Compiled By Aliazar D. (MSc in SEng) 35
Conti..
• Passing parameters to the function • Put functions within <script>….</script> tags
♠ Parameters provide value to the within the <head> section of the web page
function
♠ Refers to implicitly declared <head>
variables that can be accessed within
<script language=“JavaScript”>
function body
♠ Parameters are named variables declare functions here….
separated by commas
• Example </script>
function findMaxValue (num1, </head>
num2, num3)

Compiled By Aliazar D. (MSc in SEng) 36


JavaScript Functions
Local Variables
❑ Write a function that returns the max of three numbers
• Variables declared
function findMaxValue(num1, num2,num3)
within a function are {
var tempMax;
local //local var

if (num1 >= num2) {


• Local variable is visible tempMax = num1;
}
only within the function else {
body after it’s declared }
tempMax = num2;
if(num3 >= tempMax) {
• Commonly used to store tempMax = num3;
}
results of an return tempMax;
}
intermediate calculation
Compiled By Aliazar D. (MSc in SEng) 37
JavaScript Functions
Function calling
• Calling statement: allows to invoke already declared function.
Syntax:
[id=] functionName([Actual_parameter_list]);

• Example…somewhere in the <body>….,

var x = 1, y = 4, z = 2;

var y = findMaxValue(x, y, z);

Compiled By Aliazar D. (MSc in SEng) 38


JavaScript Functions
Return
• Return keyword tells function to return some value and exit immediately

Syntax:
return expression;

• Function can have multiple return statements but only the first can be executed in any
given function call

• Normally used to return the final result of a calculation to the calling program

Compiled By Aliazar D. (MSc in SEng) 39


JavaScript Functions
Parameter Sequence
• When calling functions, you must enter parameters in same order as specified in function
argument list.
• Notice, the actual and formal arguments are in one-to-one correspondence in order and
number

function calculateDensity(height, width, depth, mass)


{
var volume = height * width * depth;
var density = mass / volume;
return density;
}

var hth = 2, wth = 3, dth = 4, mass = 10;


var result = calculateDensity(hth, wth, mass, dth);

Compiled By Aliazar D. (MSc in SEng) 40


JavaScript Functions
Global Variables
• Global variables are those declared outside of functions
• Are visible throughout the program

var globalHello = “Hello!”;

function writeHello() {
document.write(globalHello);
}
// outputs “Hello!”

Compiled By Aliazar D. (MSc in SEng) 41


What is an Event?

❖ JavaScript's interaction with HTML is handled through events that


occur when the user or browser manipulates a page.
❖ When the page loads, that is an event. When the user clicks a button,
that click, too, is an event. Another example of events are like
pressing any key, closing window, resizing window etc.
∆ Onclick Event Type:
This is the most frequently used event type which occurs when a user
clicks mouse left button. You can put your validation, warning etc
against this event type.
42
Example:

<html>
<head>
<script type="text/javascript">
<!--
function sayHello()
{
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html> 43
JavaScript Form Validation:

❖ JavaScript can be used to validate data in HTML forms before sending


off the content to a server.
❖ Form data that typically are checked by a JavaScript could be:
Has the user left required fields empty?
Has the user entered a valid e-mail address?
Has the user entered a valid data?
Has the user entered valid length?

44
EXAMPLE:

▪ The function below checks if a field has been left empty. If the field is blank, an alert box
alerts a message, the function returns false, and the form will not be submitted:
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
var x=document.myForm.fname.value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.php" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html> 45
Conti..

• Built-In Functions
►Prompt
►Alert
►Confirm

Compiled By Aliazar D. (MSc in SEng) 46


Prompt
<!DOCTYPE html>
<html>
<body>
<p>Click the button to demonstrate the prompt box.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>
</body>
<script>
function myFunction() {
let person = prompt("Please enter your name", "Lazarus D");
if (person != null) {
document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";
}
}
</script>
</html>

Compiled By Aliazar D. (MSc in SEng) 47


Alert

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display an alert box.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
alert("Hello! I am an alert box!");
}
</script>

</body>
</html>

Compiled By Aliazar D. (MSc in SEng) 48


Confirm

<!DOCTYPE html>
<html>
<body>

<p>Click the button to see line-breaks in a confirm box.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
let text = "Press a button!\nEither OK or Cancel.";
if (confirm(text) == true) {
text = "You pressed OK!";
} else {
text = "You canceled!";
}
document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html>
49
Compiled By Aliazar D. (MSc in SEng)
Compiled By Aliazar D. (MSc in SEng) 50

You might also like