Contents
[Contents] [Tutorial]
[Object
Hierrachy] [Language]
[Expressions]
[Statements]
Introduction
Congratulations if you've made it this far. You should by now have
an idea of what JavaScript objects
are all about, know about expressions
and variables.
One last piece and JavaScript nirvana is at hand.
This section describes the glue which pulls together all the other
components into a program.
[Contents] [Tutorial]
[Object
Hierrachy] [Language]
[Expressions]
[Statements]
Simple Statements
Comments
Programmers are sometimes a stubborn bunch. They write code which
does wonderful things, sometimes in such complicated ways that even
the author can't figure it out a week later. If only the author
had inserted some documentation to explain what the code does. JavaScript
allows for comments to be put using the // symbol, or the /* and
*/ pair. Any text can be put in (though I'd be careful about puting
</SCRIPT> in them).
The // comment allows any text on the same line, following the
// to be ignored by the JavaScript interpreter.
If multiple lines are to be commented out, each can be started
by a //, or the start of the section can be marked by /*, and the
end by */
Variable Declarations
Variables,
we have seen are necessary. In JavaScript it is good style to declare
a variable using var. The declaration can also give it a value,
if that is wanted.
var myVariable = 10
var myOtherVariable, andAnother = "hello", lastOne
= 10
The above example shows that many variables can be declared on
the same line, though good style usually tries to limit that to
one per line. Once a variable is declared, we can use it in our
expressions. Here is an example of a function, we can call this
function from a button.
<SCRIPT LANGUAGE="JavaScript">
function sayHello()
{
var myVariable = "Hello "
myVariable += window.prompt("What's your name?", "")
window.alert(myVariable)
}
</SCRIPT>
<FORM>
</FORM>
That's all the simple statements. The others aren't complicated,
they just have different titles associated with them.
[Contents] [Tutorial]
[Object
Hierrachy] [Language]
[Expressions]
[Statements]
Statement Blocks
A statement block as such is not used much. Blocks are used extensively
in cooperation with other JavaScript constructs. Where a JavaScript
construct allows for one statement, we can place a {, then as much
code as we wish ending the block with a }. Statement blocks can
impose a scope, as discussed later.
[Contents] [Tutorial]
[Object
Hierrachy] [Language]
[Expressions]
[Statements]
Functions
Functions are essential to programming in JavaScript.
- A function is a block of code enclosed within the { and
} block markers.
- A function is given a name, so that we can make use of its code
by simply invoking the function by name
- A function can return a value, so we can place a call
to a function within an expression
- A function can take parameters, so that it does not do
exactly the same thing each time it is invoked.
A function is declared as follows:
- The keyword function followed by
- The function name, the rules for giving names to functions is
the same as for variables.
- An opening bracket (
- An optional list of parameters, each parameter is seperated
by a comma. A parameter can be an object,
a variable
, a call to a function or method which returns a value or
a literal.
- A closing bracket )
- A block of instructions, which embody the function's code
To exit a function the return keyword is inserted, followed
by the value we wish to return to the caller of the function. Note
that statements within the same block as the return keyword, and
placed after the keyword, are not executed.
Example
Consider the following example:
<SCRIPT LANGUAGE="JavaScript">
// function takes a number and returns the result divided by 10
function decadeCounter(decades)
{
decades /= 10
return decades
document.write("This part is never reached")
return 0 // Interpreter complains otherwise
}
// function prompts for age and gives years
function ageCounter()
{
var age = window.prompt("How old are you?", 10)
window.alert("That is " + decadeCounter(age) + "
decades!")
}
</SCRIPT>
<FORM>
</FORM>
<P>The year is 1996
<SCRIPT LANGUAGE="JavaScript">
document.write(" which adds up to ", decadeCounter(1996),
" decades")
</SCRIPT>
</P>
Here is what it looks like:
The year is 1996
The example above shows a function where the parameter list is
fixed. It is possible to write functions which take a variable number
of parameters. For such functions, the number of values it takes
is not always known when the function is written.
Variable Number Of Arguments
To write a function which takes a variable number of arguments,
it is declared as usual. A function object in JavaScript has a property
which is an array
of the parameters it has received.
For example: if we define a function called myFunction, it has
a property called arguments, which is an array. We can make use
of it as follows:
<SCRIPT LANGUAGE="JavaScript">
function myFunction()
{
document.write("You passed ", myFunction.arguments.length,
" parameters to this function<UL>")
for (var count = 0 ; count < myFunction.arguments.length
; count ++)
{
document.write("<LI>Parameter ", count,
":", myFunction.arguments[count], "</LI>")<
}
document.write("</UL>")
}
myFunction("Apples", "Pears", "Oranges")
</SCRIPT>
This produces the following output:
The for(...) statement above is one of JavaScript's looping
constructs. It allows a programmer to repeate a statement block
a specified number of times.
[Contents] [Tutorial]
[Object
Hierrachy] [Language]
[Expressions]
[Statements]
Scope
Statement blocks can be nested inside one another. If a global
variable is declared, called for example myVariable, any function
can access it and change its contents, this variable is said to
have a global scope.
A global variable can be declared within a function. This is done
by not putting the var keyword before it. It is simply assigned
a value. However it is advisable to declare global variables outside
functions, and before all functions, for legibility's sake.
The following example declares a global variable inside a function:
functions someFunction()
{
}
A global variable can be declared outside a function we can also
leave out the var keyword. The following example declares 2 global
variables, outside a function:
If there is a global variable called myVariable, and a function
happens to declare a variable,called myVariable, using the var
keyword (known as declaring a local variable), that function can
no longer access the global variable. In essence the function has
created a new variable with the same name as the global. This local
variable exists as long as the local function is executed, and can
only be seen by that local function. This local variable is said
to have a local scope: any changes made to it are not reflected
in the global variable.
If a variable is declared within a block, where that block is itself
within a function, the variable is not local to the block. The variable's
scope extends to the function's scope.
Consider the following example:
<SCRIPT>
// start of script demo
var myVariable = "Global scope"
document.write("Initialised global to: ", myVariable)
function scopeDemo()
{
var myVariable = "local value"
document.write("<UL>Set local variable to: ",
myVariable, "<br>")
{
var myVariable = 10
document.write("<UL>Set local variable to: ",
myVariable, "</UL>")
}
document.write("Local variable is: ", myVariable, "</UL>")
}
function scope2()
{
document.write("<UL>In scope2() the global is: ",
myVariable, "<BR>")
myVariable = "Change global value"
document.write("change global variable in scope2() to:",
myVariable, "</UL>")
}
scopeDemo()
document.write("In global scope, the global is: ", myVariable)
scope2()
document.write("In global scope again, the global is: ",
myVariable)
// end of script demo </SCRIPT>
The output is as follows:
Here is an explanation of what is going on:
- A global variable is declared and initialised to "Global
Scope"
- 2 functions are defined: scopeDemo() and scope2()
- scopeDemo() is called
- the function declares a local variable with the same name
as the global, the global is not visible
- the function starts a new block
- the new block declares a local, but is in fact refering
to the function's local variable
- the local block changes the value of the local
- the local block ends
- the function displays the local variable to show it's value
was changed in the local block
- the global variable is displayed to show that scopeDemo() did
not change it
- the function scope2() is called
- scope 2 has not declared a local variable, it is using the
global one
- the global variable is displayed, showing that scope2() changed
its value
[Contents] [Tutorial]
[Object
Hierrachy] [Language]
[Expressions]
[Statements]
Conditional Statements
Conditional statements allow a program to have a choice of action,
whose outcome is usually only available at run-time.
In JavaScript the syntax is as follows:
if ( condition )
{
}
else
{
}
The else part is optional
It is also OK to put another if in the else:
if ( condition )
{
}
else if ( condition )
{
}
The condition can be a boolean
expression
The layout of the { and } is subject to personal taste (see example
below)
Example:
<SCRIPT LANGUAGE="JavaScript">
function ifDemo()
{
if (window.confirm("Today is Sunday, OK?"))
{
else if (window.confirm("Today is Saturday, OK?"))
{
}
else
{
}
if (weekDay)
{
window.alert("It's a week day")
}
else
{
window.alert("You're a hard worker!")
}
}
</SCRIPT>
<FORM>
<INPUT TYPE="button" VALUE="Click Me!" onClick="ifDemo()">
</FORM>
[Contents] [Tutorial]
[Object
Hierrachy] [Language]
[Expressions]
[Statements]
Looping Constructs
JavaScript offers various ways to repeat a set of statements:
- for ( [ initialExpression ; ] [ condition ;
] [ incrementExpression ] ) { statements }
- for ( variable in object ) { statements
}
- while ( condition ) { statements
}
The [ and ] in the above list denotes an optional part, the code
should not have [ or ].
The first for is used when wish to iterate a set of statements
a specified amount of times.
- The initialExpression is a statement which is executed only
once
- The condition is a boolean expression which is evaluated once
per iteration, before executing the iteration. If the expression
evaluates to false, the loop is exited.
- the incrementExpression is a statement which is executed once
per iteration, after the statement block has been executed.
The following example lists the links up to this point in the document:
<SCRIPT LANGUAGE="JavaScript">
document.write("<UL>")
for (var count = 0 ; count < document.links.length ;
count ++)
{
document.write("<LI>", document.links[count].href,
"</LI>")
}
document.write("</UL>")
</SCRIPT>
The output is as follows:
It certainly saves coding the same line over a dozen times!
[Contents] [Tutorial]
[Object
Hierrachy] [Language]
[Expressions]
[Statements]
Objects
to be continued
[Contents] [Tutorial]
[Object
Hierrachy] [Language]
[Expressions]
[Statements]
|