Javascript: function arguments and arguments[] - javascript

I'm a Javascript novice so please excuse the fundamental question.
I'm working my way through 'Professional Javascript For Web Developers' and in Chapter 3, "Understanding Arguments" section, it discusses accessing function arguments with the arguments[] keyword.
One of the examples shows that you can modify the values in arguments[]:
function twoNums(num1, num2) {
arguments[1] = 10;
console.log(arguments[0] + num2);
}
twoNums(4,8); output = 14
But it goes on to say that "This effect goes only one way: changing the named argument does not result in a change to the corresponding value in arguments."
However, changing the code to:
function twoNums(num1, num2) {
num2 = 10;
console.log(arguments[0] + arguments[1]);
}
twoNums(4,8); output = 14
results in the same output so the value in 'arguments[1]' is definitely changing.
Is this:
an error in the book?
an error in my understanding?
something that has changed in Javascript since the writing of the book?
Thanks,
Neil
ANSWERED: A combination of answers solved my problem. Thanks everyone.

It is supposed to work that way, unless in strict mode:
function foo(a) {
"use strict";
console.log(a, arguments[0]);
a = 10;
console.log(a, arguments[0]);
arguments[0] = 20;
console.log(a, arguments[0]);
}
foo(1);
// output:
// 1 1
// 10 1
// 10 20
The ES5 specification addresses that on section 10.6:
NOTE 1 For non-strict mode functions the array index (defined in 15.4) named data properties of an arguments object whose numeric name values are less than the number of formal parameters of the corresponding function object initially share their values with the corresponding argument bindings in the function’s execution context. This means that changing the property changes the corresponding value of the argument binding and vice-versa. This correspondence is broken if such a property is deleted and then redefined or if the property is changed into an accessor property. For strict mode functions, the values of the arguments object’s properties are simply a copy of the arguments passed to the function and there is no dynamic linkage between the property values and the formal parameter values.
Maybe it worked differently on ES3 (the previous version), but I doubt it (since they had to add a special case for strict mode).
Interesting fact: the presence of an eval call in the function can influence how the arguments object behave in some browsers, which is extremely weird. The use of the non-standard functionName.arguments reference also has an impact. See Why does an unexecuted eval have an effect on behavior in some browsers?, and my answer to it.

There is an error in the book, by the looks of things: if you reassign any of the arguments passed, the arguments object will change (both reference the same value).
Perhaps, though, what was meant in the book was this:
function f(n1, n2)
{
arguments[0] = 2;
console.log(arguments[0] + arguments[1]);
}
f(1, 2);//logs 4
f(1234,2);//logs 4
But, honestly, it shouldn't really matter. The arguments object should be treated as a read-only object. It's a good idea to uphold the mantra "Don't change objects you don't own" in JS. It's a bad idea trying to change the Object.prototype, as it is not the best of ideas to change the behaviour of any object (console, window...) by deleting and adding methods at random.
If you want to get some more details on arguments, or anything else MDN is there to help. I've not looked at all code examples there, but AFAIKT there's no code that effectively changes the arguments object.
Some time ago I think I read an article my Douglas Crockford on the matter, where he gave an example of how changing the arguments object actually lead to unexpected behaviour (arguments swapping places and all that).
Edit:
I'd thought I'd not go into strict mode, but as bfavaretto's answer pointed out: strict-mode actually does make the arguments object a read-only object. That's terrific news, and now I have all the more reason to love the way JS is going. ES6 will introduce block scoping and probably make the arguments object read-only all the time (at least, I hope it will).

it will work that way only in strict mode..
"use strict"
The Arguments object has one very unusual feature. In non-strict mode,
when a function has named parameters, the array elements of the
Arguments object are aliases for the parameters that hold the function
arguments. The numbered elements of the Arguments object and the
parameter names are like two different names for the same variable.
Changing the value of an argument with an argument name changes the
value that is retrieved through the arguments[] array. Conversely,
changing the value of an argument through the arguments[] array
changes the value that is retrieved by the argument name. Here is an
example that clarifies this:
function f(x) {
console.log(x); // Displays the initial value of the argument
arguments[0] = null; // Changing the array element also changes x!
console.log(x); // Now displays "null" } This is emphatically not the behavior you would see if the Arguments object
were an ordinary array. In that case, arguments[0] and x could refer
initially to the same value, but a change to one would have no effect
on the other.
This special behavior of the Arguments object has been removed in the
strict mode of ECMAScript 5. There are other strict-mode differences
as well. In non-strict functions, arguments is just an identifier. In
strict mode, it is effectively a reserved word. Strict-mode functions
cannot use arguments as a parameter name or as a local variable name,
and they cannot assign values to arguments.
Here is a great (and recent) article on this topic:
https://www.inkling.com/read/javascript-definitive-guide-david-flanagan-6th/chapter-8/function-arguments-and
I Suggest you use it :)

Related

Array.length vs arrayinstance.length in javascript

I'm a bit confused by the Array.length property (i.e. a property named length on the Array function object) and array_instance.length (i.e. a property named length on instance of array object)
So what is difference between the two length property and when should/shouldn't we use them?
Edit 1:
there is also a length property on Array.prototype object. I am so confused.
Edit 2
Just to paint a clearer picture, here are the different length properties I have found
Edit 3
This is one of the follow up questions I asked in the comment section, but I think the question is important to fully understanding length property, so I have copy-pasted here in the main section
Follow up question:
Array.prototype.hasOwnProperty('length') and Array_instance.hasOwnProperty('length') return true, does that mean there are two length properties, one on array_instance, one on Array.prototype object, with the array_instance.length overshadowning the Array.prototype.length?
functions have a .length property which corresponds to how many arguments they are expecting. For example:
const unary = (a) => {
}
const binary = (a, b) => {
}
console.log(unary.length);
console.log(binary.length);
So the Array constructor has a length of 1 because it expects one parameter to be passed to it (namely, the size of the array).
array objects also have a .lengthproperty, which is unrelated other than having the same name. This property says how large the array currently is.
I really think a lot of the other answers have covered everything needed here, but as it seems the OP hasn't had what they see a a clear answer, I will try to set everything out, somewhat extensively - but as clearly as I can - in order to clarify. (Apologies if anyone thinks I am "stealing" their answer - I assure you that this is not the intention, and I'm deliberately not looking at them as I type this, but I've certainly read most of them and even upvoted a few.)
Array.length
This has already been well-covered above. Array is a native JS function, which you can use for creating arrays. It's less common then simply defining an array literal (and as far as I know there is no reason it would ever be preferable), but instead of var a = [1,2,3] you are allowed to do this:
var a = Array(1,2,3);
console.log(a);
Note in passing that you don't want to do this to create a singleton array, there is an utterly mad gotcha of a special case when you supply exactly one parameter which happens to be an integer:
var a = Array(5);
console.log(a);
Although that shows what appears to be an array of 5 undefined values in whatever JS console implementation SO uses, that's not actually quite what has been created (nor what is displayed in the current version of Chrome). I'm getting way off-topic but I'll refer you to Kyle Simpson's excellent walkthrough of the madness.
Anyway, since Array is a function, as others have already observed, it has a length property as all functions do. I'm really not sure why it evaluates to 1 though - for a user-defined function it is the number of arguments the function was formally declared with, but since Array like all native JS functions isn't actually implemented in JS, I couldn't tell you how the implementation actually works. Clearly it can take any number of arguments and thus is a rather "exotic" function. I don't think that Array.length would ever be useful, no matter what value was arbitrarily assigned to it, but it seems that most implementations go for 1, even if the specification leaves it open. (I'm not enough of a spec devotee to know if this is actually defined in there or left up to implementations.)
arrayinstance.length
This is just the feature of arrays that we know and use all the time. All JS arrays get this property - note that, although it is a property rather than a method (that is, it is not a function), it nevertheless "auto-updates" as the array gets longer/shorter:
var a = [1,2,3];
console.log(a.length);
a.push(4);
console.log(a.length);
a.pop();
a.pop();
console.log(a);
console.log(a.length);
Although as I said, Javascript's native constructors are not implemented in terms of JS itself, you could implement this kind of behaviour by defining a getter (at least since ES5).
Array.prototype.length
To fully explain what Array.prototype (and similar objects) is would take me deep into how Javascript's object system work. Suffice to say here that, unlike class-based languages (and JS does not have classes, even in ES6, despite the class syntax allowing us often to pretend it does), JS does not have the usual concept of "inheritance" that so-called OO languages do. In JS's version (sometimes called "prototypal inheritance"), what happens it that each object has an "internal prototype" which references some other object - and if you try to access a property on that object which it doesn't have, the JS engine will look at that "prototype object" for the property and use its value instead.
It's actually a very simple mechanism, but there are a number of things in the language which confuse this, one of them being the fact that functions (which are also objects) have a property called prototype - which does not point to the real "prototype" object which gets consulted if a nonexistent property is referenced on the function object. (A normal function foo has Function.prototype is the object that it delegates to - not foo.prototype.) However, if you declare a function foo, an object called foo.prototype is created - which is basically an empty, nondescript object. Its significance is that if the function foo is used as a "constructor" - that is, if you make an object by calling new foo() - foo.prototype will then be the object that JS will look up properties (including methods) on if any object constructed from foo happens to fail a property lookup.
This is why, at least in pre-ES6 code, you quite frequently saw this kind of pattern:
function foo(a,b) {
this.a = a;
this.b = b;
}
foo.prototype.add = function() {
this.a = this.a + this.b;
}
var myFoo = new foo(1,2);
console.log(myFoo.a);
myFoo.add();
console.log(myFoo.a);
myFoo.add();
console.log(myFoo.a);
console.log(myFoo.hasOwnProperty("add"));
Despite appearances, myFoo doesn't actually have a method add in this example - as confirmed by the final console.log. When the JS engine fails to find the property though, it goes to myFoo's "internal prototype", which happens to be foo.prototype. And that's why the method works, as it would on any object constructed from foo.
Anyway, this is leading up to the fact that Arrays, which could be (although almost never are) constructed by calling new Array (I didn't use the new operator above, but I could have done, this is a case where it makes no difference), therefore delegate to Array.prototype. All those array methods that you know and love don't "really" exist on the arrays you call them on:
var a = [1,2,3];
a.push(4);
console.log(a);
console.log(a.hasOwnProperty("push"));
console.log(Array.prototype.hasOwnProperty("push"));
So array methods only work because those methods are actually found on the Array.prototype object, to which all arrays delegate for property/method access if the lookup doesn't succeed on the array itself. (And this is why, if you look up any of them on MDN, the top of the page always says Array.prototype.<method_name>, because that's where the method "really" lives.)
A drastic demonstration of this (please DON'T do this in production code!)
// you're used to doing this, and it works:
[1,2].push(3);
console.log("that went fine");
// vandalism on a grand scale!
Array.prototype.push = undefined;
// now you can'tse the "push" method anymore!
[1,2,3].push(4);
But I'm going to end on something of an anticlimax. The above is true for array methods - but the length array property isn't a method. As observed above, it's just a "plain" (non-function) property, which "magically" behaves somewhat like a function call. As observed in the OP, .length property accesses don't delegate as the method calls shown above do, the property exists on each array in itself.
So why does Array.prototype still itself have a length property? Well, Array.prototype is actually itself an array. In fact, that's not the only thing:
Array.prototype.push(1);
console.log(Array.prototype);
Function.prototype();
notice that Array.prototype.push(1) ends up with Array.prototype being the singleton array [1]. So Array.prototype is "kind of like" the empty array (it's not exactly the same, because it has all those methods mentioned above directly accessible on the object itself, which a "normal" empty array doesn't). And with Function.prototype, although calling it didn't output anything, the fact that no TypeError was raised proves that it really is a function (it's actually a "no-op" function, like function() {}, but once again with various methods diretcly on it - the methods which every function has access to, such as .call and .bind).
Anyway, to cut the digression short, since Array.prototype is - as far as ordinary array properties are concerned, at least - an empty array, this explains why it has a length property, and why it's equal to 0.
I hope this clears things up, as well as demonstrating some of the more intriguing parts of Javascript.
The first part has already been answered, Array constructor is a function and functions have a .length property.
For the second, Array.prototype.length, it's a bit more obscur...
Array.prototype is actually an Array:
console.log(Array.isArray(Array.prototype)); // true
Array.prototype.push('hello');
console.log(Array.prototype.length); // 1
console.log(Array.prototype[0]); // "hello"
As to why is it an Array? Because specs say so:
The Array prototype object is an Array exotic objects and has the internal methods specified for such objects. It has a length property whose initial value is 0 and whose attributes are { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }..
There is also a note specifying that it is for compatibility reasons with previous versions of the specs.
As to why is was designed as being an Array? I have no really strong idea...
Disclaimer:
I have tried to show how constructor and instance works in general. But in fact, they have huge difference between different constructors.
Any constructor has been set its length with the value specified by the spec. Specially most of them are set to 1:
Number.length // 1
Object.length // 1
Function.length // 1
Array.length // 1
// etc.
Similarly,
Array.constructor.length // 1
// etc.
Like #Kaiido pointed out in the comment, you can see some constructor length is set:
Document.length // 0
Int8Array.length // 3
Date.length // 7
And you may also notice the length of the instance is undefined as they are not set. - It's out of the scope though.
let d = new Date
d.length === undefined // true
See at the bottom for relevant references.
But when you have an instance of it, then you're creating a new value of it:
typeof new Array === typeof Array.prototype // true
typeof new Function === typeof Function.prototype // true
// etc.
So, when you use an instance it has no length value set because it has no any parameters:
let arr = new Array // Array.prototype
arr.length === 0 // true
But when you use an instance with parameter, then you have the length property with the value of parameters
let arr = new Array(20)
arr.length === 20 // true
let func = function(a1,a2,a3,a4){}
func.length === 4 // true
// etc.
So now, you have been wondering why the constructor has length value equal to 1?
It's because the spec has set the value to be 1 initially.
Every built-in Function object, including constructors, has a length property whose value is an integer. Unless otherwise specified, this value is equal to the largest number of named arguments shown in the subclause headings for the function description, including optional parameters.
The value of the [[Prototype]] internal slot of the Object constructor is the intrinsic object %FunctionPrototype%.
Besides the length property (whose value is 1),
See these references:
Standard built in objects,
19.1.2 Properties of the Object Constructor,
19.2.2 Properties of the Function Constructor,
etc.
Also, you can see the prototype has length to 0, you already know it why in the preceding example.
Though, here's just a reference stating that:
19.2.3 Properties of the Function Prototype Object
And there some constructor whose length is set different. This is the out of scope of this answer. Though, here's a reference for the date constructor:
20.3.3 Properties of the Date Constructor
So, it's totally up to the spec how they have been defined.
Array.length
Array is constructor which means its type is "function". You try the checking it console.
typeof Array //"function"
According to MDN
The length property indicates the number of parameters expected by the function.
As the Array function expects single argument so Array.length = 0
array_instance.length
The length property of an object which is an instance of type Array sets or returns the number of elements in that array
As we know that arrays are actually objects so objects can have properties. The property length is on the instance of array.
Now second question you may ask why we don't get the length properties of array using Object.keys or for..in loop. The answer is because this property is not Enumerable.
let arr= [];
//this.property 'length2' will not be shown in for..in or Object.keys();
Object.defineProperty(arr,'length2',{
value:'length2 for test',
enumerable:false
})
//this property 'x' will be displayed in for..in loop and Object.keys()
Object.defineProperty(arr,'x',{
value:'length2 for test',
enumerable:true
})
console.log(Object.keys(arr)); //["x"]
Array.prototpe.length
According to the DOCS
The initial value of Array.prototype.constructor is the standard built-in Array
The Array prototype object is itself an array; its [[Class]] is "Array", and it has a length property (whose initial value is +0) constructor
Actually Array.prototype is an array. And remember array is always object. So it can have properties. The methods of the Array are stored in form of key:value. and there is no element in that array so it Array.prototype.length returns 0. If you push() some elements into it you will see it as array.
console.log(Array.prototype.length) //0
console.log(Array.isArray(Array.prototype)) //true
//adding element to array
Array.prototype.push('x')
console.log(Array.prototype.length) //1
As I explained in second parts you can hide properties of Object by setting enumerable:false. All the methods are keys of Array.prototype But now shown in for..in loops.
Array.length
For the number of properties in the array or the length property of an object which is an instance of type Array sets or returns the number of elements in that array.
Array.prototype.length
Inherited number of properties in the array. When you check Array.length you're actually checking Array.prototype.length

If all JavaScript types are objects, then why are numbers be passed by value?

In articles about closures, you will often see closures being created inside of loops using self-invoking functions to pass the iterator variable to a returned function expression in order to create a closure around the value of the iterator variable at the time the self-invoking function was invoked, rather than its value after the loop finishes. Here is an example:
var func = [];
for (var i = 0; i < 3; i++)
{
func.push((function(j){ return function(){ console.log(j); }; })(i));
}
// Logs
// 0
// 1
// 2
// to the console
for (var i = 0; i < func.length; i++)
{
func[i]();
}
This technique works with both numbers and strings, based on my simple experiments. However, the same technique does not work with plain JavaScript objects. If an object is passed to a self-invoking function and referenced in a function expression, changes to the enclosed object are visible in the function expression because the value passed to the self-invoking function was a reference to an object and not a copy of the object, as is the case with numbers and strings.
I can understand why this technique would not work with a variable that stores an object, but I don't understand why this technique should work with numbers and strings, whose prototype chains terminate with Object.
Does this mean that strings and numbers are just special cases of objects that are handled differently by the interpreter, or am I suffering from a fundamental misconception?
First, it is not true that "all JavaScript types are objects". Primitive strings, numbers, and boolean values are not objects.
Second, everything in JavaScript is pass-by-value. It's important to understand what "pass-by-value" means. It means that when a function is called, like this:
var someVariable = something;
someFunction(someVariable); // <--- this is the function call
then what the language does is copy the value of someVariable and pass that copy to the function. What a "pass-by-reference" language would do is pass a reference to that variable to the function. Because a copy of the value of the variable is passed to the function in a pass-by-value world, the function has absolutely no way to modify the value of someVariable. In a "pass-by-reference" language, it does.
To some extent, C++ lets you employ either parameter passing scheme. JavaScript does not.
The fact that in JavaScript variables have object references as values sometimes does not mean the language is pass-by-reference. I know that that seems like a silly pedantic distinction, but it's important to understand that "pass-by-value" and "pass-by-reference" are precise terms used to describe language semantics. If they don't have precise meanings, they're useless for that purpose.
One more thing: JavaScript implicitly wraps string, number, and boolean primitive values in wrappers of the corresponding String, Number, and Boolean types when the primitive values are used as if they're objects. That's what happens when you do something as common as:
var five = "hello".length
The left-side operand of the . operator has to be an object, so there's no special-case here: there's an implicit promotion of the primitive string value to a String instance. (What the runtime really does under the covers, well, we can't tell and we shouldn't care. Conceptually, a temporary wrapper object is created, used, and thrown away.)
In javascript there are 6 primitive types: string,number,boolean,null,undefined,symbol - new in ECMAScript 2015. However there are Object wrapper classes for these primitives. All 6 except null and undefined have wrapper classes. Reference These primitive types are passed by value not by reference per the javascript design.

Why should you pass Math as the first argument to Math.max.apply?

I'm going through John Resig's JavaScript ninja tutorial and on #51 I see this:
// Find the largest number in that array of arguments
var largestAllButFirst = Math.max.apply( Math, allButFirst );
allButFirst is just a small array of integers. I believe I understand what apply does, but I can't understand why Math is being passed as an argument to apply.
The first parameter of the .apply is the context. Inside the function body the this keyword will reference that value.
Example:
function sum(a){ return this + a; }
sum.apply(1, [1]); // will return 2
// or with .call
sum.call(1, 1); // also returns 2
By default if you call Math.max the context (the this keyword) is automatically set to Math. To keep this behavior Math is passed as the first parameter in apply.
Passing it Math is not necessary, anything will work here. Math indicates the context of the operation, however max does not require a context. This means that Math.max.apply(undefined, allButFirst) will also work. See this answer.
From Mozilla docs:
fun.apply(thisArg, [argsArray])
thisArg: The value of this provided for the call to fun. Note that this
may not be the actual value seen by the method: if the method is a
function in non-strict mode code, null and undefined will be replaced
with the global object, and primitive values will be boxed.
So, in your example, Math is being used as the context for the function (if the keyword this is used inside).
If no thisArg is used, then the default is the global object. So, it is good practice to give some context if possible.

Is it possible to overwrite javaScript primitive data type?

Question is self explanatory. I know it is possible to extend primitive data types such as string but is it possible to overwrite it?
This is a question that has been asked in an interview.
No, you cannot overwrite anything. EcmaScript defines the primitive types Undefined, Null, Boolean, Number, and String; these are internal and will be used regardless of what you are doing (for example overwriting the global String constructor). Type conversion and evaluation of literals does not rely on any public functions but uses only these internal types and the algorithms specified for them.
Of course, if someone does string coercion with String(myval) instead of ""+myval assigning to the global String variable will have an effect on that code. Any internal use would still point to the "old" function.
If you were talking about prototype objects for the primitive types (when used as objects), those are not overwritable as well. You may extend those objects, but as soon as you assign to e.g. Number.prototype you just have lost a reference to the actual, original number protype object. Example spec for The Number constructor:
The [prototype] of the newly constructed object is set to the original Number prototype object, the one that is the initial value of Number.prototype (15.7.3.1)
Yes (edit: almost). Open up a Javascript console (F12 if you're using Chrome) and type
String = function(){alert('bang!')};
You can overwrite (edit: almost) everything in Javascript — even the window global context! evil.js is a library that uses this trick to rewrite many native objects as possible.
Needless to say, this is extremely dangerous. I performed the String remapping code above, and since writing it down I've caused over 520 Javascript errors (and I've seen 'bang' alerted quite a few times). Native objects are used everywhere, and you shouldn't modify these in case 3rd party code relies on them in ways you don't know about. This is one of the reasons Prototype.js lost popularity — because its extension of native objects would often work against the expectations of other code.
Edit: Factually incorrect assertion that absolutely everything could be overwritten, as pointed out in Bergi's answer. Edits made inline.
You can extend prototypes of native types.
String.prototype.moo = function() {
console.log( 'Moo!' )
};
'Cow says'.moo();
>> "Moo!"
However you cannot directly overwrite constructors of built-in types unless you overwrite the reference to the entire object:
String = function() {
console.log( 'Custom function.' )
};
new String( 'Hello!' );
>> "Custom function."
>> String {} // now you've broken your website ;)
...but still:
'Wat?!'
>> "Wat?!" // you can still create strings by typing letters in quotes
So... the answer is "yes but no". You can mess with native types (Number, Date, String...) but you cannot re-define them entirely from scratch. They're a part of JS engine that you're using (most likely native C++ code) and this brings some limitations.
Possible like this but you must always succeed without side effects.Not good practice.
function Array() {
var obj = this;
var ind = 0;
var getNext = function(x) {
obj[ind++] setter = getNext;
if (x) alert("Data stolen from array: " + x.toString());
};
this[ind++] setter = getNext;
}
var a = ["private stuff"];
// alert("Data stolen from array: private stuff");

Performance penalty for undefined arguments

I quite often have optional arguments in functions, but some testing is showing a huge performance hit for them in firefox and safari (70-95%). Strangely, if I pass in the literal value undefined then there is no penalty. What could be happening here? I wouldn't have thought that it was a scope chain issue as they are inherently local to the function. Am I to start passing undefined into every optional argument?
jsPerf: http://jsperf.com/function-undefined-args/2
For a function like this:
function threeArgs(x, y, z) {
return x + y + z;
}
that's called like this:
threeArgs(1, 2, 3);
the optimizer is free to make the choice to generate no code at all. It's fairly easy for it to determine that there are no side effects, because the function simply references its parameter values and returns the result of a simple expression. Since the return value is ignored, there's no reason for the runtime to do anything at all.
Beyond that, if the code were:
something += threeArgs(1, 2, 3);
the optimizer might decide to generate code roughly equivalent to:
something += 6;
Why? Because the call was made with numeric constants, and it can safely fold those at code generation time. It might be conservative on that, because numbers are weird, but here they're all integers so it could well do this. Even if it didn't, it could safely inline the function:
something += 1 + 2 + 3;
When there's a parameter missing, however, it may be that the optimizers bail out and generate a real function call. For such a simple function, the overhead of the function call could easily account for a large difference in performance.
By using variables instead of constants in a test, and by actually using the return value of the function, you can "confuse" the optimizer and keep it from skipping the call or pre-computing the result, but you can't keep it from inlining. I still think that your result is interesting for that reason: it exposes the fact that (as of today anyway) those optimizers are sensitive to the way that functions are invoked.
I think what could explain the performance difference is the way arguments are passed to a function object: via the arguments object. When not passing any arguments, JS will start by scanning the arguments object for any of the given arguments, when those are undefined, The arguments prototype chain will be scanned, all the way up to Object.prototype. If those all lack the desired property, JS will return undefined. Whereas, passing undefined explicitly, sets it as a property directly on the arguments object:
function foo(arg)
{
console.log(arguments.hasOwnProperty('0'));
}
foo();//false'
foo('bar');//true
foo(undefined);//true
I gather that's the reason why passing undefined explicitly tends to be faster.

Categories

Resources