Changing JavaScript function's parameter value using arguments array not working

  • A+
Category:Languages

I am learning JavaScript and am pretty confused with the arguments property array. Let me elaborate.

I have a function that takes a single argument and returns it. When I am passing the parameter and reassigning it using arguments[0] = value, it's updating the value.

function a(b) {   arguments[0] = 2;   return b; } console.log(a(1)); //returns 2

But when I call the same function with no parameters it return undefined.

function a(b) {   arguments[0] = 2;   return b; } console.log(a()); //returns undefined

also if I pass undefined then also the value is updating.

function a(b) {   arguments[0] = 2;   return b; } console.log(a(undefined)); //returns 2

I thought if you do not pass a parameter to a JavaScript function it automatically creates it and assigns the value to undefined and after updating it should reflect the updated value right? Also a() and a(undefined) are the same thing right?

 


Assigning to arguments indicies will only change the associated argument value (let's call it the n-th argument) if the function was called with at least n arguments. The arguments object's numeric-indexed properties are essentially setters (and getters):

http://es5.github.io/#x10.6

Italics in the below are my comments on how the process relates to the question:

(Let) args (be) the actual arguments passed to the [[Call]] internal method

  1. Let len be the number of elements in args.

  2. Let indx = len - 1.

  3. Repeat while indx >= 0, (so, the below loop will not run when no arguments are passed to the function:)

(assign to the arguments object being created, here called map:)

    1. Add name as an element of the list mappedNames.
    1. Let g be the result of calling the MakeArgGetter abstract operation with arguments name and env.
    1. Let p be the result of calling the MakeArgSetter abstract operation with arguments name and env.
    1. Call the [[DefineOwnProperty]] internal method of map passing ToString(indx), the Property Descriptor {[[Set]]: p, [[Get]]: g, [[Configurable]]: true}, and false as arguments.

So, if the function is invoked with no arguments, there will not be a setter on arguments[0], so reassigning it won't change the parameter at index 0.

The same sort of thing occurs for other indicies as well - if you invoke a function with 1 parameter, but the function accepts two parameters, assigning to arguments[1] will not change the second parameter, because arguments[1] does not have a setter:

function fn(a, b) {   arguments[1] = 'bar';   console.log(b); } fn('foo');

So

a() and a(undefined) are the same thing right?

is not the case, because the second results in an arguments object with a setter and a getter on index 0, while the first doesn't.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: