Javascript function arguments handling

arguments

In JavaScript we don’t have any method to check our parameters and arguments.

Earlier tutorial, We have learned that functions can have parameters; like –



functionName(parameter1, parameter2, parameter3) {
    code to be executed
}

but suppose that we missed one parameter or arguments like –



function msg(name, msg) {

    if (msg === undefined) {
          msg = "Welcome to Javascript";
    } 
}

Here you are handling the missing case. But how to manage if we have too many arguments.
So for that condition, we have a special object; arguments object

How it works



function sum () {
	
	for (var i = 0, sum = 0; i < arguments.length; i++) {
		sum += arguments[i];
	}

	return sum;
}

console.info(sum(1, 2, 3, 4, 5)); // 15

Now you can see arguments works like an array. But it’s not an array. It has an only length property. So be careful when you are using arguments.



function isArray () { 

	return Array.isArray(arguments);
}

console.info(Array.isArray()); // false

So If we want to use this like an array so we need follow these steps –


var args = Array.prototype.slice.call(arguments);
var args = [].slice.call(arguments);

How to use



function isArray () {
   var args = Array.prototype.slice.call(arguments);
   var args = [].slice.call(arguments);

   return Array.isArray(args);
}

console.info(isArray()); // true

You May Also Like

About the Author: Pankaj Bisht