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]
?
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.
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.
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.
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.
"Why does changing the value of
what
change the value ofarguments[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!"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With