JavaScript Reference: Functions


Defining Functions

  • Use: Perform a task described by statements, with or without parameters.
  • Format: function function_name( parameters ) { statement(s) }
  • Examples:
    // This function takes in a parameter x and returns x cubed:
    function cube( x ) {
    	return x*x*x
    }
    	
    // This function does not require a parameter, and creates a pop-up when called:
    function getInfo( ) {
    	prompt( "What is your name?" )
    }
    
    // This function takes in two parameters, and prints their sum/concatenation to the terminal:
    function printSum( x,y ) {
    	console.log( x+y )
    }
    
    // This function takes in a number x, and returns (x+1)^3 by calling the cube function defined above:
    function plusOneCube( x ) {
    	var y = cube( x + 1 )
    	console.log(y)
    }

Return

  • Use: Return a value to the caller.
  • Example:
    function cube( x ) {
    	return x*x*x
    }
    	
    var twoCubed = cube(2)	// twoCubed now has value 8	
    
    // A function may also return a boolean value, true or false. The following example creates a function that returns true if a value is found in an array:
    
    var myArray = [1,2,3,4,5,6,7,8,9,10]
    
    function inTable( a, x ) {
    	var in = false	
    	for ( i = 0; i < a.length; i++ ) {
    		if ( a[i] === x ) {
    			in = true;
    			break;
    		}
    	}
    	return in	
    }
    
    inTable( myArray, 6 )	// would return true
    inTable( myArray, 11 )  // would return false

Functions as Variables

  • Use: Call a function within another statement.
  • Example:
    function firstLetter( s ) {
        return s.charAt(0)
    }
    
    console.log("The first letter of dog is "+firstLetter('dog'))
    would result in
    The first letter of dog is d