Javascript

March 4, 2009

Introduction:
Javascript is a client side, lightweight programming language, also known as a scripting language. Its function is to allow a heightened level of interactivity in static HTML pages. It can be embedded directly into a  HTML file, or referenced and used from an external file.

External Referencing:
To reference an external file, the following code is used:

<script type=”text/javascript” src=”helloworld.js”></script> 

If.. Else Statement:
This is used when the execution of code is based upon a conditional statement. If the statement returns true, the first block of code will be executed. If not, the else block of code will be executed.

Loops:
There are two types of loops –

  • For -  Runs a loop for a specified amount of time. The block of code will be iterated as many times as has been specified
  • While – Runs while a condition is true. This is not necessarily a specified amount of time, and can lead to infinite loops. The block of code will be iterated until the statement is false.

However, loops can be stopped in one of two ways:

  • Break; If used inside a nested loop, this command will discontinue all loops and continue to any code that follows outside the loop.
  • Continue; If used inside a nested loop, this command will discontinue the loop it is placed in, but will continue to the code in the loop outside it.

Function:
The use of a function is to stop the browser from executing the code on page load. This means that the function must be ‘called’ to execute its code. The syntax for creating a function is:

function functionname(var1, var2, …, varX)
{
code
}

Parameters:
Parameters may or may not be used with a function. A function may be called without parameters: function(); or have parameters: function(parameter).
This allows code to be minimised if paramters are used correctly. Ie:


<script language=”JavaScript”>
function box1(){alert(“You just opened box #1″);}
function box2(){alert(“This is box #2″);}
</script>
<a href=”#” onClick=”box1()”>Box #1</a><br>
<a href=”#” onClick=”box2()”>Box #2</a>

could be minimised to:

<script language=”JavaScript”>
function box(whichText)
{alert(whichText);}
</script>
<a href=”#” onClick=”box(‘You just opened box #1′)”>

Return Values:
The return statement is used to specify the value that is returned from the function. It is referenced by:

return variable;

Leave a Reply