0% found this document useful (0 votes)
98 views53 pages

Chapter 7 - JAVASCRIPT - Hamid

This document discusses JavaScript functions and flow control. It covers: 1. Functions allow reusable blocks of code that can be called from different places. Functions take arguments as input and can return values. 2. Conditional statements like if/else and switch statements allow different code blocks to run based on conditions. Loops like for, while, and do/while loops repeatedly execute code. 3. Examples demonstrate writing and calling functions, and using conditional statements and loops to control program flow in JavaScript.

Uploaded by

Asad Akhlaq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
98 views53 pages

Chapter 7 - JAVASCRIPT - Hamid

This document discusses JavaScript functions and flow control. It covers: 1. Functions allow reusable blocks of code that can be called from different places. Functions take arguments as input and can return values. 2. Conditional statements like if/else and switch statements allow different code blocks to run based on conditions. Loops like for, while, and do/while loops repeatedly execute code. 3. Examples demonstrate writing and calling functions, and using conditional statements and loops to control program flow in JavaScript.

Uploaded by

Asad Akhlaq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

JavaScript: Client-Side

Scripting

 Chapter 7

Textbook to be published by Pearson ©


Ed2015
in early
Pearson
2014
http://www.funwebdev.com
Objectives

1 Flow Control

2 Functions

3 JavaScript
Objects
 Section 1 of 3

Flow Control
Flow control content
 Conditional statements are used to perform different
actions based on different conditions.

 Very often when you write code, you want to perform


different actions for different decisions. You can use
conditional statements in your code to do this.

 Conditional Statements Loops


– if.. Statement For Loop
– if.. else Statement While Loop
– if.. else if Statement Do.. While Loop
– switch case Statement
Flow Control
 Conditional Statements
– if statement - use this statement if you want to execute
some code only if a specified condition is true.
– if...else statement - use this statement if you want to
execute some code if the condition is true and another
code if the condition is false.
– if...else if....else statement - use this statement if you
want to select one of many blocks of code to be
executed.
– switch statement - use this statement if you want to
select one of many blocks of code to be executed.
Conditional Statements
if statement:

 Use the if statement to execute some code only if a specified condition


is true.

Syntax:

if (condition)
{
code to be executed if condition is true
}

 Note that if is written in lowercase letters. Using uppercase letters (IF)


will generate a JavaScript error!
 Notice that there is no ..else.. in this syntax. You tell the browser to
execute some code only if the specified condition is true.
if statement:
Example:
<html><head><title></title></head><body>
<script type="text/javascript">
var total=0;
var even=0;
document.write( "Raygan");
for (x=1; x<=10; x++)
{
total = total + x;
if ((x%2)==0) {
even = even + x; }
}
document.write( "The total sum: "+total+"<br>");
document.write( "The sum of even values:"+ even );
</script>
</body>
</html>
Conditional Statements
if.. else statement:
Syntax:
if (expression)
{
statement(s) to be executed if expression is true
}
else
{
statement(s) to be executed if expression is false
} Example: <script type="text/javascript">

var total = prompt("Enter your total", "50");

if (total >=50)
{alert("PASSED")}
else
{alert("FAILED")}

</script>
Conditional Statements
if.. else if statement:

Syntax:
if (expression 1)
{ statement(s) to be executed if expression 1 is true }
else if (expression 2)
{ statement(s) to be executed if expression 2 is true }
else if (expression 3)
{ statement(s) to be executed if expression 3 is true }
else
{ statement(s) to be executed if no expression is true }
if.. else if statement:
Example:
<script type="text/javascript">

var age = prompt("Enter your age", "25");


if (age >0 && age <= 3)
{alert("WOW Baby")}
else if (age >= 4 && age < 13)
{alert("You are child")}
else if (age >= 13 && age < 31)
{alert("You are young ;)")}
else if (age >= 31 && age < 46)
{alert("Middle Age :/")}
else if (age >= 46 && age < 71)
{alert("You are old :(")}
else if (age >= 71 && age < 101)
{alert("Get ready for a new world!!!")}
else
{alert("Ageless")}
</script>
Conditional Statements
switch case statement:
Syntax:

switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
switch case statement:
Example: <body> <script type="text/javascript">
var flower=prompt("Which flower whould you like to
buy?","rose");
switch (flower) {
case "rose":
alert(flower + " costs 10TL");
break;
case "daisy":
alert(flower + " costs 3TL");
break;
case "orchild":
alert(flower + " costs 25TL");
break;
default:
alert("SORRY =( there is no such flower in our shop");
break; }
</script>
</body>
For Loop: You can put all the three parts in a single line separated by a
semicolon.
Syntax:
for (initialization; test condition; iteration statement)
{
statement(s) to be executed if test condition is true
}
Example:
<script type="text/javascript">
document.write("<h2>Multiplication table from (1 to 10)</h2>");
document.write("<table border=2 width=50%");

for (var i = 1; i <= 10; i++ ) { //this is the outer loop


document.write("<tr>");
document.write("<td>" + i + "</td>");

for ( var j = 2; j <= 10; j++ ) { // inner loop


document.write("<td>" + i * j + "</td>");
}
document.write("</tr>");
}
document.write("</table>");
</script>
For Loop:

Example Output:
The while Loop:
loops through a block of code as long as a specified condition is true.
Syntax:
while (condition)
{
statement(s) to be executed if expression is true
}

Example: <script type="text/javascript">


var total=0;
var i=0;
var j;

while (i<= 10) {


j=i%2;
if (j!== 0)
{
total+=i;} i++
}

document.write("Total of odd numbers between 1-


10:" +" +total);
</script>
The do..while Loop:
• similar to the while loop except that the condition check happens at the
end of the loop.
• this means that the loop will always be executed at least once, even if
the condition is false.
Syntax: Example:
do <script type="text/javascript">
{
var num = 0;
statement(s) to be executed;
} do{
while (condition); num = num + 5;
document.write(num + "<br />");
}
Output:
while (num < 25);
5
</script> 10
15
20
25
 Section 2 of 3

JavaScript Functions
Functions
 A function is a reusable piece of code that will be executed
when called for.

 A function consists of a piece of computation that takes 0


or more arguments (input data) and returns a value
(output data).

 Functions can be embedded in the <head></head> and


within the<body> </body> tag.

A function can be called from anywhere from within the page or even from other
pages if the function is stored in an external JavaScript (.js) file.
FUNCTIONS: WRITING CODE FOR LATER
• If we want to re-run some code again and again from different places,
then put that code in a function and call this function.

• Functions are like little packages of JavaScript code waiting to be called


into action.

• Some predefined functions are alert(), prompt() and confirm(). These


all are available on the top level window object.

• Functions can return values. Values returned by predefined window


functions are: undefined, user input string or empty string or null,
true or false.
Functions
 To create a function
function funcName( arg1, arg2, . . . )
{
JavaScript Code
Must have the Must have the
}
same name! same number!
Reserved word
 To call a function
– funcName( argExp1, argExp2, . . . )
– Each argument is assigned to each parameter
– The body { } of the function is executed.
An example function

function pay(payRate,hours)
{ Variables
return payRate*hours;
}

The return Statement


 The return statement is used to specify the value that is returned from the
function.

Example: function prod(a,b)


{
x=a*b
return x
}
product=prod(2,3)
Built-In Functions
 eval(expr)
– evaluates an expression or statement
• eval("3 + 4"); // Returns 7 (Number)
• eval("alert('Hello')"); // Calls the function alert('Hello')

 isFinite(x)
– Determines if a number is finite

 isNaN(x)
– Determines whether a value is “Not a Number”
Built-In Functions
 parseInt(s)
 parseInt(s, radix)
– Converts string literals to integers
– Parses up to any character that is not part of a valid integer
• parseInt("3 chances") // returns 3
• parseInt(" 5 alive") // returns 5
• parseInt("How are you") // returns NaN
• parseInt("17", 8) // returns 15

 parseFloat(s)
– Finds a floating-point value at the beginning of a string.
• parseFloat("3e-1 xyz") // returns 0.3
• parseFloat("13.5 abc") // returns 13.5
An example function

Therefore a function to raise x to the yth power might be


defined as:

function power(x,y){
var pow=1;
for (var i=0;i<y;i++){
pow = pow*x;
}
return pow;
}
And called as
power(2,10);
An example function

<SCRIPT TYPE = "text/javascript">


var input1 = window.prompt( "Enter first number", "0" );
var input2 = window.prompt( "Enter second number", "0" );
var input3 = window.prompt( "Enter third number", "0" );
var value1 = parseFloat( input1 );
var value2 = parseFloat( input2 );
var value3 = parseFloat( input3 );
var maxValue = maximum( value1, value2, value3 );
document.writeln( "First number: " + value1 +
"<BR>Second number: " + value2 +
"<BR>Third number: " + value3 +
"<BR>Maximum is: " + maxValue );
// maximum method definition (called from above)
function maximum( x, y, z ) {
return Math.max( x, Math.max( y, z ) );
}
</SCRIPT>
Function Demo

<Script language=“JavaScript”>
function sayHello()
{
window.alert("Hello " + demoform.title.value)
}
</Script>

<INPUT type=“button” name=“go” value=“GO!” onclick=sayHello() >


Example
<html>
<head>
<Script language=“JavaScript”>
function sayHello()
{
alert("Hello " + demoform.title.value)
}
</Script></head>
<body><form>
<INPUT type=button value=GO! name=go onclick=sayHello() >
</form></body>
</html>
 Section 3 of 3

Javascript Objects
JavaScript Objects
• Objects exist as a way of organizing variables and functions into
logical groups. If we create objects to organize some variables and
functions then the terminology changes slightly, now they are called
properties and methods respectively.
JavaScript Objects
 An object is just a special kind of data, with properties and methods.

Accessing Object Properties


– Properties are the values associated with an object.
– The syntax for accessing the property of an object is:

objectName.propertyName

This example uses the length property of the String object to find the
length of a string:

var message="Hello World!";


var x=message.length;

 The value of x, after execution of the code above will be: 12


Java Script Object Methods
 Accessing Objects Methods
– Methods are the actions that can be performed on objects.
– You can call a method with the following syntax:
objectName.methodName()

 This example uses the to UpperCase() method of the String object, to


convert a text to uppercase:
var message="Hello world!";
var x=message.toUpperCase();

 The value of x, after execution of the code above will be:

HELLO WORLD!
Creating JavaScript Objects

 With JavaScript you can define and create your own


objects.
 There are 2 different ways to create a new object:

1. Define and create a direct instance of an object.


2. Use a function to define an object, then create new
object instances.
Objects and Properties
Creating a Direct Instance
 The following example creates a new instance of an object, and adds four
properties to it:
<!DOCTYPE html>
<html>
<body>
<script>
var person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
document.write(person.firstname + " is " + person.age + " years old.");
</script>
</body> </html>
Object Methods
Alternative syntax (using object literals)

<!DOCTYPE html>
<html>
<body>
<script>
person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"}
document.write(person.firstname + " is " + person.age + " years old.");
</script>
</body>
</html>

36
Using an Object Constructor
 The following example uses a function to construct the object:
<!DOCTYPE html>
<html>
<body>
<script>
function person(firstname,lastname,age,eyecolor)
{ this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
myFather=new person("John","Doe",50,"blue");
document.write(myFather.firstname + " is " + myFather.age + " years old.");
</script>
</body>
</html>
Objects Included in JavaScript
A number of useful objects are included with JavaScript including:
• Array
• Boolean
• Date
• Math
• String
• Dom objects
Arrays
• An Array object is used to store a set of values in a single
variable name.
• An Array object is created with the new keyword.
• An array can be created as:
var MyArray=new Array()

• An array can also be created by specifying the array size.


var MyArray=new Array(3)
Defining Arrays
 An array can be created in three ways.
 The following code creates an Array object called myCars:
1: Regular:
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

2: Condensed:
var myCars=new Array("Saab","Volvo","BMW");

3: Literal:
var myCars=["Saab","Volvo","BMW"];
Array Methods and Properties
 The Array object has predefined properties and methods:
var x=myCars.length // the number of elements in myCars
var y=myCars.indexOf("Volvo") // the index position of "Volvo"

 Data can be entered into an array as:


var MyArray=new Array()
MyArray[0]=“Paul”
MyArray[1]=“Sam”
MyArray[2]=“Niel”
 Data can also be entered into an array as:
var MyArray=new Array(“Paul”,”Sam”, “Niel”)
Accessing Arrays
• You can refer to a particular element in an array by referring
to the name of the array and the index number.
• The index number starts at 0 .
alert ( greetings[0] );
• One of the most common actions on an array is to traverse
through the items sequentially. Using the Array object’s length
property to determine the maximum valid index. We have:
for (var i = 0; i < greetings.length; i++){
alert(greetings[i]);
}
A list of names from the user, storing each name entered in an array.

<!DOCTYPE html>
<html lang="en">
<head>
<title> Example Array</title>
</head>
<body>
<script>
var inputName = "";
var namesArray = [];
while ((inputName = prompt("Enter a name", "")) != "") {
namesArray[namesArray.length] = inputName;
}
namesArray.sort();
var namesList = namesArray.join("<br/>");
document.write(namesList);
</script>
</body>
</html>
Math
• The Math class allows one to access common mathematic functions
and common values quickly in one place.
• This static class contains methods such as max(), min(), pow(), sqrt(),
and exp(), and trigonometric functions such as sin(), cos(), and
arctan().
<html><body>
<p id="demo">Click the button to round the number 2.5 to its nearest
integer.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML=Math.round(2.5);
}
</script> </body> </html>

• The getElementById() method accesses the first element with the specified id.
• The innerHTML property sets or returns the inner HTML of an element
Methods of Math object
String
The String class has already been used without us even knowing it.
Constructor usage
var greet = new String("Good"); // long form constructor
var greet = "Good"; // shortcut constructor
Length of a string
alert (greet.length); // will display "4"
String
Concatenation and so much more

var str = greet.concat("Morning"); // Long form concatenation


var str = greet + "Morning"; // + operator concatenation
Many other useful methods exist within the String class, such as
• accessing a single character using charAt()
• searching for one using indexOf().
Strings allow splitting a string into an array, searching and
matching with split(), search(), and match() methods.
Date Object
• The Date object is used to work with dates and times.
• An instance of the Date object with the "new" keyword.
• An instance of Date object can be created as:
var myDate=new Date() <!DOCTYPE html>

var myDate=new Date("Month dd, yyyy hh:mm:ss") <html>


<body>
var myDate=new Date("Month dd, yyyy")
<script>
var myDate=new Date(yy,mm,dd,hh,mm,ss)
var d=new Date();
var myDate=new Date(yy,mm,dd)
document.write(d);
var myDate= new Date(milliseconds) </script>
</body>
</html>
Create a web page display current time in hour, minutes, and seconds.

<!DOCTYPE html>
<html lang="en">
<head>
<title>Display Current Time</title>
</head>
<body>
<div id="output"></div>
<script>
function updateTime() {
var date = new Date();
var value = date.getHours() + ":" +
date.getMinutes() + ":" +
date.getSeconds();
document.getElementById("output").innerHTML = value;
}
setInterval(updateTime, 1000);
</script>
</body>
</html>
Date Object Example
Use getFullYear() to get the year

<!DOCTYPE html>
<html> <body>
<p id="demo">Click the button to display the full year of todays date.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var d = new Date();
var x = document.getElementById("demo");
x.innerHTML=d.getFullYear();
}
</script>
display the full year of todays date
</body> </html>
Object getDay()
Use getDay() and an array to write a weekday, and not just a number.
<html>
<body>
<p id="demo">Click the button to display todays day of the week.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var d = new Date();
var weekday=new Array(7); display todays day of the week.
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
var x = document.getElementById("demo");
x.innerHTML=weekday[d.getDay()]; }
</script> </body> </html>
 Next Section

The Document Object Model


(DOM) & Form Validation
What you Learned
1 Flow Control

2 Functions

3 JavaScript
Objects

You might also like