Javascript Object Oriented Design - Javascript Function Parameters








JavaScript functions can accept any number of parameters.

Javascript function parameters are stored as an array-like structure called arguments.

arguments can grow to contain any number of values.

The values are referenced via numeric indices, and there is a length property to determine how many values are in arguments.

The arguments object is available inside any function.

The named parameters in a function exist for convenience and don't limit the number of arguments that a function can accept.

The arguments object is not an instance of Array and therefore doesn't have the same methods as an array.

Array.isArray(arguments) always returns false.

JavaScript doesn't ignore the named parameters of a function either.

The number of arguments a function expects is stored on the function's length property.

The length property indicates the number of parameters it expects.





Example

The following code shows how to use arguments and function length.


function myMethod(value) { /*  www .  j av  a2  s .co m*/
    return value; 
} 

console.log(myMethod("java2s.com!"));        
console.log(myMethod("java2s.com!", 2));    
console.log(myMethod.length);        

myMethod = function() { 
    return arguments[0]; 
}; 

console.log(myMethod("java2s.com!"));        
console.log(myMethod("java2s.com!", 2));    
console.log(myMethod.length);        

The code above generates the following result.

The following code shows how to create a function to sum any number of parameters.

         
function sum() { //ww  w  . j  a v a2 s  . co m
    var result = 0, 
        i = 0, 
        len = arguments.length; 
    while (i < len) { 
        result += arguments[i]; 
        i++; 
    } 
    return result; 
} 

console.log(sum(1, 2));         
console.log(sum(13, 14, 15, 16));
console.log(sum(5,0));          
console.log(sum());    

The code above generates the following result.





Overloading

JavaScript functions can accept any number of parameters, and the types of parameters a function takes aren't specified.

JavaScript functions don't actually have signatures.

Javascript functions don't support overloading.

The following code shows what happens when declaring two functions with the same name:

 
function myMethod(message) { 
    console.log(message); 
} 

function myMethod() { 
    console.log("Default message"); 
} 

myMethod("Hello!");     

The code above generates the following result.

In JavaScript, when defining multiple functions with the same name, the one that appears last in your code wins.

We can simulate function overloading by using the arguments object.


function writeLine(message) { 
    if (arguments.length === 0) { 
        message = "Default message"; 
    } 
    console.log(message); 
} 
writeLine("Hello!");     
writeLine("");

The code above generates the following result.