Instructor: Amadou O. Wane
Last update: 09/24/01
Lecture4
Variable Scope
A variable that is defined outside of
a function is a global variable. A variable that is defined inside of a
function is a local variable. What does this mean? Global variables can be
used anywhere in the document that is currently loaded in the browser.
They can be declared in the HEAD section and used in any function or even
in the BODY section. Local variables can only be used in the function that
declares them.
//Varible scope
//Local scope vs. global scope
var g = 99;//Global variable
function my_addition(a,b)
{ var l = a + b; //Local variable
document.write("The c variable is:" + l);
document.write("<br>The g variable is:" + g);
}
my_addition(10,20);
//-----------------------------------------------
If Statement
The if statement is one of the most used features of JavaScript. It is
basically the same in JavaScript as it is in other programming languages.
If you are new to programming, you should spend some time understanding
how the if statement works. You use the if
statement in JavaScript to make decisions. The syntax for it is as
follows:
if (condition){
statements
}
//If Statements
/*if (condition)
{ statements
}
else
{ statements
}*/
var my_age = 99;
if (my_age >= 18)
{ document.write("<br>You are an adult");
}
The if
keyword identifies this as an if statement. The condition
in the parenthesis ( ) is evaluated to
determine if true, and if so then the statements
inside the curly braces { } are executed,
otherwise they are skipped and the programs continues with the first line
after the if statement.
An optional else statement can be
included with the if statement as follows:
if
(condition){
statements
}
else{
statements
}
In this case, the statements
inside of curly brackets { } after the else
keyword are executed if the condition of the if
statement is false.
Switch Statement
var d = new Date()
theDay=d.getDay()
switch (theDay)
{
case 5:
document.write("Finally Friday")
break
case 6:
document.write("Super Saturday")
break
case 0:
document.write("Sleepy Sunday")
break
default:
document.write("I'm really looking forward to this weekend!")
}
var myColor = "unknown";
var hexColor = "FF0000";
switch(hexColor)
{ case
var myColor = "Red";
}
|