Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: why does changing an argument variable change the `arguments` "array"?

Tags:

javascript

Consider:

> function hello(what) {
.     what = "world";
.     return "Hello, " + arguments[0] + "!";
. }
> hello("shazow")
"Hello, world!"

Why does changing the value of what change the value of arguments[0]?

like image 351
David Wolever Avatar asked Apr 19 '12 02:04

David Wolever


People also ask

What happens to any extra parameters passed in to a JS function?

You can call a Javascript function with any number of parameters, regardless of the function's definition. Any named parameters that weren't passed will be undefined.

Which one option will convert the arguments to an array?

Object. values( ) will return the values of an object as an array, and since arguments is an object, it will essentially convert arguments into an array, thus providing you with all of an array's helper functions such as map , forEach , filter , etc.

Is arguments an array in JavaScript?

arguments is an array-like object, which means that arguments has a length property and properties indexed from zero, but it doesn't have Array 's built-in methods like forEach() or map() . However, it can be converted to a real Array , using one of slice() , Array. from() , or spread syntax.

Can a function change the value of its arguments?

Some functions work by modifying the values of their arguments. This may be done to pass more than one value back to the calling routine, or because the return value is already being used in some way.


1 Answers

"Why does changing the value of what change the value of arguments[0]?"

Because that's how it's designed to work. The formal parameters are directly mapped to the indices of the arguments object.

That is unless you're in strict mode, and your environment supports it. Then updating one doesn't effect the other.

function hello(what) {
    "use strict"; // <-- run the code in strict mode
    what = "world";
    return "Hello, " + arguments[0] + "!";
}
hello("shazow"); // "Hello, shazow!"
like image 76
3 revs, 2 users 96%user1106925 Avatar answered Nov 10 '22 08:11

3 revs, 2 users 96%user1106925