I’m writing a function that checks if arguments are zero, and it doesn’t seem to work correctly. Note: Using Chrome as my browser, but this code should be cross-browser supported.
// check all arguments, and make sure they aren't zero
function zeroCheck(arg1, arg2) {
var i, argsLen = arguments.length;
for (i = 0; i <= argsLen; i += 1) {
if (arguments[i] === 0) {
// This is where it doesn't behave as I expected
arguments[i] = 1; // make arg1 = 1
}
}
console.log(arg1); // arg1 = 0
}
zeroCheck(0, 2);
I was expecting arg1 to be equal to 1, but it is still equal to 0.
From the ECMA-262 spec:
But if you read the technical details of how the
argumentsobject is set I think you’ll find it is based on how many arguments are actually passed to the function when it is called, not how many named arguments are declared, so usingargumentsand a loop to check the value of each named parameter might not work if they’re not all passed in. Though in your case if you’re testing specifically for0it should work since parameters that are not passed will beundefinedrather than0.Having said that, exactly how the
argumentsobject actually behaves depends on the browser. Chrome doesn’t follow the spec.