JavaScript Functions


JavaScript functions allow us to define a block of code and we can call it as many times as we want.

A JavaScript function can be declared by using the function keyword, followed by a unique function name, a list of parameters and a statement block surrounded by curly braces.

Syntax:

    function functionName (parameter1, parameter2, ...)
    {
        //code to be executed
    }    


Example 1:

    function hello()
    {
        alert (“Hello everyone!”);
    }    

We can call above function as hello().



Example 2:

    function getSquare (num)
    {
        return ( num * num );
    }    

We can call above function as getSquare(5) and it will return the square of 5 i.e.25.


Anonymous functions

An anonymous function is an unnamed function i.e.it does not have any name.

It must be assigned to a variable.

Example:

    var msg = function()
    {
        alert(“Hello Everyone!”);
    }    

The above anonymous function can be invoked as msg().