JavaScript Functions

JavaScript is the scripting language that is used in conjunction with HTML.

JavaScript can either be:

Embedded within the HTML document by using the <script> element

  • <script type=”text/javascript”></script>

Or linked within an external script by declaring the link in the head

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

These scripts are then accessed by calling the functions contained within them.

 


 

When using JavaScript you will write code in sections called functions. Functions can be seen as separated pieces of code within your .js file that can each be accessed individually.

Functions are created by writing function, the name you wish to call it, followed by set of brackets and finished off with a pair of braces – which contain the function’s code . This function can then be called by its name followed again by a set of brackets. The example below is a function that simply creates an alert with the String “Hello World” in it:

HelloWorld();

function HelloWorld()

{

alert(“Hello World”);

}

 


 

When using functions you will want to send variables back and forth between them. This can be done by passing parameters and sending back return values.

When creating a function you want to bring a variable into you must specify what the variable will be called when it has been passed into the function. This is done by placing what you want it to be named in the brackets after function and its name. The example below is the same as the last example nexcept this one takes in the text String variable it is going to print out:

function HelloWorld(textToPrint)

{

alert(textToPrint);

}

 

To send a variable that you are currently using you can call the function the same way as before but instead of leaving the brackets empty place the name of the variable you want to pass in there. The example below demonstrates this:

HelloWorld(textToPrint);

function HelloWorld(textToPrint)

{

alert(textToPrint);

}

 

To send a variable or value back to the place that a function was called from you can type return followed by a pair of brackets containing the variable name or value. The example below is of a function that returns a value after multiplying the incoming variable by 100.

function Multiply(integerToMultiply)

{

integerToMultiply = integerToMultiply * 100;

return( integerToMultiply );

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: