Monday, January 18, 2016

JavaScript Function: Parameters and Arguments


This article will cover JavaScript function parameters and arguments. Please refer to the previous article for an introduction to JavaScript Function.

Function Parameters

In JavaScript, a function declaration can have 0 to many parameters, for example:
// function body is excluded for brevity
function clear_dom() {...}      // function declaration with zero parameter
function display_car(car){...}  // function declaration with one parameter
function add(a,b){...}          // function declaration with two parameters
Function Arguments

The function arguments refer to the variables/values being passed into the function when it is invoked. For example:
// 1 and 2 are number literals being passed
// as arguments to the add() function
var result = add(1,2); 

// the {...} is an object literal being passed
// as arguments to the display_car() function
display_car({ make: "Honda", model: "Civic"}); 
Function Arguments variable

Within the function body, JavaScript provides implicit variable called "arguments". This implicit variable "arguments" refer to an object that contains a list of values being passed as function arguments to this function. This is very handy if the number of parameters are not known beforehand, for example:
function sum(){
  if(arguments === undefined) {
     return 0;
  }

  var result = 0;
  for(var i=0; i < arguments.length; i++) {
    result += arguments[i];
  }
  
  return result;  
}

var noResult = sum();           // noResult is 0
var sumResult = sum(1,2,3,4,5); // sumResult is 15
Note that while arguments function variable appears to look like an array, it is not an array object. Here's the defining characteristics of the arguments function variable:
  • It is an object
  • It derives from Object prototype (not array)
  • It looks like an array but it is not an array
  • It always exist within the function body
  • It scopes is Function Scope (once it leaves function, it's gone)
  • It has 2 properties: length and callee
    • length: refers to the number of arguments being passed
    • callee: refers to the method/function itself (in above example: sum() function)
Function Arguments Variable Optimization Killer

One note when it comes to Function arguments variable is that it must never be passed around to avoid "leak" (leak refers to optimization killer, not memory leak).
function leakOptimizationKiller(){
   return arguments;
} 

function leakOptimizationKiller(){
  var args = Array.prototype.slice.call(arguments);
}
The reason why this cancels out JS engine optimization is that the arguments variable is originally stored in the stack. In the above examples, JS engine is forced to create a reference of the arguments object in the heap as well.

No comments:

Post a Comment