Functions

Functions

Overview

Defining a function

function functionName(parameterList) { // function body - code that does the work goes here return data; // optional }

Calling a function

// example of passing-by-value function test(x) { x = 2 * x; console.log(x); // displays: 2 * what was passed in } var x = 3; console.log(x); // displays: 3 test(x); // will display 6 inside test console.log(x); // displays: 3 (x was not modified) // example of passing-by-reference function test2(obj) { obj.x = 2 * obj.x; console.log(obj.x); } var obj = { x: 3 }; console.log(obj.x); // displays: 3 test2(obj); // will display 6 inside test console.log(obj.x); // displays: 6 (x was modified) // example of handling a variable number of arguments function add() { var sum = 0; for (var i=0,count=arguments.length; i<count; i++) { if (! (typeof arguments[i] == 'number')) { sum = 0; break; } sum += arguments[i]; } return sum; } console.log(add()); // displays: 0 console.log(add(5, 3)); // displays: 8 console.log(add(5, "Hi", 3)); // displays: 0 console.log(add(1,2,3,4,5,6,7,8,9,10)); // displays: 55 console.log(add("15")); // displays: 0

Anonymous, nested, and immediately invoked functions

// example of an anonymous function used to handle an event // The window's background color is changed when the user clicks in the window window.onclick = function() { document.body.style.backgroundColor = "#0000ff"; }; // example of an anonymous function assigned to a variable var cube = function(x) { return x * x * x; }; console.log(cube(2)); // displays: 8 console.log(cube(3)); // displays: 27 // example of an anonymous function assigned to an object property var obj = { nm: "Humanoid", greet: function() { alert("Greetings " + this.nm); } }; obj.greet(); // displays: Greetings Humanoid // example of a nested function // Note: this function does NO error checking of the argument function sumOfSquares(arr) { // function sq can't be seen outside sumOfSquares function sq(x) { return x*x; } var sum=0; for (var i=0; i<arr.length; i++) sum += sq(arr[i]); return sum; } console.log(sumOfSquares([3,4])); // displays: 25 // example of an immediately invoked function // nothing in the function can be seen outside the function (function() { var abc=5; console.log(abc); })(); // displays: 5

Recursive functions

// Computing a factorial is a common recursion example // The factorial of a positive integer N (written N!) is defined // as N! = N * (N-1) * (N-2) * ... * 1 // Note that this means 5! = 5 * 4!, 3! = 3 * 2!, etc. // // A recursive definition is: // 0! = 1 // 1! = 1 // N! = N * (N-1)! // where N > 1 function fac(n) { return n<2 ? n : n * fac(n-1); } fac(3); // returns: 6 fac(4); // returns: 24 fac(5); // returns: 120

Exploring recursion

Try to write recursive JavaScript functions for these other commonly used icons of recursion: