CS553 - JavaScript

What You Should Already Know

What is JavaScript?

Are Java and JavaScript the Same? NO!

What can a JavaScript Do?

A Simple JavaScript Hello World

How to Put JavaScript Into an HTML Page using the write object

What is document.write and what does it mean?

<html> <body> <script type="text/javascript"> document.write("Hello World!") </script> </body> </html>

Note: If we had not entered the <script> tag, the browser would have treated the document.write("Hello World!") command as pure text, and just write the entire line on the page.

Do You Have to End Statements With a Semicolon?

How to Handle Older Browsers

Browsers that do not support JavaScript will display the script as page content. To prevent them from doing this, use the HTML comment tag:

<script type="text/javascript"> <!-- document.write("Hello World!") //--> </script>

The two forward slashes at the end of comment line (//) are a JavaScript comment symbol.

This prevents the JavaScript interpreter from interpreting the line.

Where to Put the JavaScript

Scripts in the head section

<html> <head> <script type="text/javascript"> .... </script> </head>

Scripts in the body section

<html> <head> </head> <body> <script type="text/javascript"> .... </script> </body>

Scripts in both the body and the head section

<html> <head> <script type="text/javascript"> .... </script> </head> <body> <script type="text/javascript"> .... </script> </body>

Using an External JavaScript Script

Variables Rules for variable names

Conditional/Branching/Selection Statements

Sometimes you want to perform different actions for different decisions

The If Statement

You should use the if statement if you want 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!

Example 1

<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10
var d=new Date()
var time=d.getHours()

if (time<10)
{
document.write("<b>Good morning</b>")
}
</script>

Example 2

<script type="text/javascript">
//Write "Lunch-time!" if the time is 11
var d=new Date()
var time=d.getHours()

if (time==11)
{
document.write("<b>Lunch-time!</b>")
}

</script>

Note: When comparing variables you must always use two equals signs next to each other (==)!

Notice that there is no ..else.. in this syntax. You just tell the code to execute some code only if the specified condition is true.

If...else Statement

If you want to execute some code if a condition is true and another code if the condition is not true, use the if....else statement.

Syntax

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

}

Example

<script type="text/javascript">
//If the time is less than 10,
//you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.
var d = new Date()
var time = d.getHours()

if (time < 10)
{
document.write("Good morning!")
}
else
{
document.write("Good day!")
}
</script>

If...else if...else Statement

You should use the if....else if...else statement if you want to select one of many sets of lines to execute.

Syntax

if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true

}
else
{
code to be executed if condition1 and
condition2 are not true
}

Example

<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>")
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>")
}
else
{
document.write("<b>Hello World!</b>")
}

</script>

The JavaScript Switch Statement

The switch statement is used if you want to select one of many blocks of code to be executed.

Syntax

switch(n)
{
case 1:
  execute code block 1
  break
case 2:
  execute code block 2
  break
default:

  code to be executed if n is
  different from case 1 and 2
}

This is how it works

Example

<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
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 looking forward to this weekend!")
}

</script>

JavaScript Operators

Arithmetic Operators

Operator Description Example Result
+ Addition x=2
y=2
x+y
4
- Subtraction x=5
y=2
x-y
3
* Multiplication x=5
y=4
x*y
20
/ Division 15/5
5/2
3
2.5
% Modulus (division remainder) 5%2
10%8
10%2
1
2
0
++ Increment x=5
x++
x=6
-- Decrement x=5
x--
x=4

Assignment Operators

Operator Example Is The Same As
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y

Comparison Operators

Operator Description Example
== is equal to 5==8 returns false
=== is equal to (checks for both value and type) x=5
y="5"

x==y returns true
x===y returns false

!= is not equal 5!=8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than or equal to 5>=8 returns false
<= is less than or equal to 5<=8 returns true

Logical Operators

Operator Description Example
&& and x=6
y=3

(x < 10 && y > 1) returns true

|| or x=6
y=3

(x==5 || y==5) returns false

! not x=6
y=3

!(x==y) returns true

String Operator

A string is most often text, for example "Hello World!". To stick two or more string variables together, use the + operator.

txt1="What a very"
txt2="nice day!"

txt3=txt1+txt2 

The variable txt3 now contains "What a verynice day!".

To add a space between two string variables, insert a space into the expression, OR in one of the strings.

txt1="What a very"
txt2="nice day!"
txt3=txt1+" "+txt2
or
txt1="What a very "
txt2="nice day!"
txt3=txt1+txt2

The variable txt3 now contains "What a very nice day!".

Conditional Operator

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

Syntax

variablename=(condition)?value1:value2 

Example

greeting=(visitor=="PRES")?"Dear President ":"Dear "

If the variable visitor is equal to PRES, then put the string "Dear President " in the variable named greeting. If the variable visitor is not equal to PRES, then put the string "Dear " into the variable named greeting.

Popup Boxes

Alert Box

Syntax:

alert("sometext")

Confirm Box

Syntax:

confirm("sometext")

Prompt Box

Syntax:

prompt("sometext","defaultvalue")

JavaScript Functions

Functions


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>

If the line: alert("Hello world!!") in the example above had not been put within a function, it would have been executed as soon as the line was loaded. Now, the script is not executed before the user hits the button. We have added an onClick event to the button that will execute the function displaymessage() when the button is clicked.

You will learn more about JavaScript events in the JS Events chapter.


How to Define a Function

The syntax for creating a function is:

function functionname(var1,var2,...,varX)
{
some code
}


The return Statement

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

A function does NOT necessarily have to return anything to the caller

But, functions that are going to return a value must use the return statement.

var1, var2, etc are variables or values passed into the function. The { and the } defines the start and end of the function.

Note: A function with no parameters must include the parentheses () after the function name:

function functionname()
{
some code
}

Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with the exact same capitals as in the function name.


Example

The function below should return the product of two numbers (a and b):

function prod(a,b)
{
x=a*b
return x
}

When you call the function above, you must pass along two parameters:

product=prod(2,3)

The returned value from the prod() function is 6, and it will be stored in the variable called product.

The assignment statement will copy the contents of prod to the variable called product.

JavaScript Loops

In JavaScript there are two different kind of loops:

Loops in JavaScript are used to execute the same
block of code a specified number of times or while a specified
condition is true.

The for Loop

The for loop is used when you know in advance how many times the script will iterate through the loop.

Syntax

for (var=startvalue;var<=endvalue;var=var+increment)
{
    code to be executed

}

Example
Explanation:

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

var i=0
for (i=0;i<=10;i++)
{
document.write("The number is " + i)
document.write("<br />")
}
</script>
</body>
</html>

Result

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

The while loop

Loops in JavaScript are used to execute the same
block of code a specified number of times or while a
specified condition is true.

The while loop is used when you want the loop to execute
and continue executing while the specified condition is true

while (some condition is true)

Explanation:

<html>
<body>
<script type="text/javascript">
var i=0
while (i<=10)
{
document.write("The number is " + i)
document.write("<br />")
i=i+1
}

</script>
</body>
</html>

Result

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

The do...while Loop