Javascript functions

Javascript functions

Learn how to create Javascript functions to increase modularity and re-usability within your code


Functions are used in programming to give developers a way to easily reuse pieces code within your scripts and applications. Functions usually define a piece of code along with a name that can be called anywhere within your script as many times as needed to run that code. Functions can also have the ability to receive extra values when called that can alter the way in which the code within runs.


In Javascript, functions have many uses that can make coding far more efficient and convenient, they can be called both from within your script and from your HTML document.


Defining Javascript functions


In Javascript, a function is defined using the

function

keyword followed by the unique name of the function, followed by parenthesis "()" that can contain function parameters, followed by the code you want to be executed when the function is called surrounded by curly brackets "{}". The proper format for functions within your script looks like this:


function functionName(){     
    // your code here     
}     


The code within your function should be indented to ensure readability. Code statements within a function work the same as they would outside the function, you can declare variables, perform arithmetic and use loops just as you would anywhere else in your script.


function test(){     
    var num1 = 5;     
    var num2 = 6;     
    alert( "5 + 6 = " + ( num1 + num2 ) );     
}     


Calling Javascript functions from within your script


To execute the code within a function from within your script, the function must be called by making reference to the function name followed by parentheses that contain a list of arguments (can be left empty when no parameters are included, see below).


functionName();


So if you wanted to call the test function we created earlier, you could use the following code:


test();

This will display "5 + 6 = 11"


Functions can be called from anywhere within your script, as long as it is within the same scope, a function can even be called before it is even defined within your script.


test();    
    
function test(){    
    alert( "hello world" );    
}    


More on function scope later in this tutorial.


Calling Javascript functions from within your HTML using events


A useful feature in HTML is the ability to run Javascript code through

event attributes such as onclick

or onchange. Using these attributes you can also call functions that are defined within your script.


<element event="functionName();">    
    
</element>


For example, say you wanted to assign a function to the "onclick" event of an <h1> element that outputs the contents of that element, you could use the following code:


<h1 onclick="headingContents()">Hello world</h1>    
    
<script>    
        
    function headingContents(){    
        alert( document.getElementsByTagName( "h1" )[ 0 ].innerHTML );    
    }    
    
</script>    

When the heading element is clicked it will invoke the headingContents function, this function will retrieve the element using document.getElementsByTagName() and get the contents using the innerHTML attribute of the element.


Passing values to a function using parameters


In Javascript and most other programming languages, you can pass values to a function using parameters. A parameter is like a variable that is limited to a specific function and can be given a value when the function is called.


In Javascript you can declare parameters within the parentheses after the function name, each parameter should be separated by a comma. You can include as many parameters as needed.


function functionName( param1, param2, ... ){   
    // function code here   
}   


Once declared, parameters can be used just like normal variables within your function. To give values to your parameters, you must include them when calling the function, these given values are referred to as arguments.


As an example let's create a simple function that takes two numbers as arguments and adds them together:


function addNums( num1, num2 ){   
    alert( "The sum of the given numbers is: " + ( num1 + num2 ) );   
}   
   
addNums( 5, 6 );   


In Javascript, you can also provide

default values for your function parameters

.


Returning values from your function


It can be useful for functions to be able to return a value that can be used outside the function after being called and execution has completed. This can be accomplished using the return keyword.


The return keyword can pass a value to wherever it was called in your script, this value can be used or stored just like any other. return is also used to halt the execution of functions, so ensure that you place this statement after it has completed.


To return a value from a function, simple use the return keyword followed by the value.


return value;


As an example of how you might use this statement, let's create another function that adds two numbers, but instead of displaying the result at the end of the function, it will just return the result, this result will be stored in a variable and then displayed manually outside the function.


function addNums( num1, num2 ){   
    return ( num1 + num2 );  
    // code after the return statement will not execute  
}   
   
var result = addNums( 5, 6 ); 

The value of the "result" variable will be 11 when this script is executed.


Javascript function scope


The scope of a function refers to where that function can be accessed from within your script. Similar to

variable scope

, it determines the accessibility of functions.


When you create a function in the global scope of your script (not within any other block of code ie. function, loop) it can be called from anywhere within your script, this includes other within other functions or even within itself.


function test1(){  
    console.log( "test1" );  
}  
  
// calling a function from within another function  
function test2(){  
    console.log( "test2" );  
    test1();  
}  
  
// a function calling itself  
function test3( loop ){  
    console.log( "test3" );  
    if( loop ){  
        test3( false );  
    }  
}  
  
test1();  
test2();  
test3( true );  

This script will output the following to the console:


test1  
test2  
test1  
test3  
test3  


The first function in the example simply outputs the string "test1" to the console and does not make use of other global functions.


The second function makes a call to function 1 after displaying its own string, resulting in the output "test2" and "test1".


The third function is more complicated to understand, it makes a call to itself after displaying its own string. This is known as

function recursion

which is possible in many programming languages.


A function can make calls to itself as many times as needed, but you should be careful not to cause an infinite loop within your script. In the above example, an if statement is used to ensure that the function only makes a call to itself once and does not cause an infinite loop.


When a function is declared within a code block such as another function, it will then no longer belong to the global scope but rather to the local scope of that code block. If you try and access a function outside of its scope, it will not work.


function globalFunc(){ 
    function localFunc(){ 
        // function code 
    } 
    // this will work 
    localFunc(); 
 
    // this will also work 
    globalFunc(); 
} 
 
// this will work 
globalFunc(); 
 
// this will not work 
localFunc();

When calling the globalFunc function, it will not also execute the localFunc unless explicitly called within globalFunc as well. If you try to execute localFunc from outside globalFunc, it will result in an error.



Christopher Thornton@Instructobit 7 years ago
or