1

When I set arugments[0] = chewie; arguments[1] = luke it prints:

Chewbacca

Chewbacca

Han Solo

Chewbacca

And what I expected was the following:

Chewbacca

Luke Skywalker

Han Solo

Chewbacca

function starWars(luke, darth, han, chewie) {

   arguments[0] = chewie;
   arguments[1] = luke;

   document.write(arguments[0] + "<br>");
   document.write(arguments[1] + "<br>");
   document.write(arguments[2] + "<br>");
   document.write(arguments[3] + "<br>");
 
} 

starWars("Luke Skywalker", "Darth Vader", "Han Solo", "Chewbacca");

Can anyone explain me in details why it is not working as I expected?

2
  • 1
    You should not be assigning values to arguments manually. In almost every case, it's no longer necessary to use the arguments object in ES2015 or later
    – Mulan
    Commented May 7, 2017 at 10:11
  • 1
    Because arguments[0] and luke are the exact same thing. Not two references to the same value, but basically both are kind of the same variable. If you change arguments[0], luke will also be changed; and vice versa. So much for the knowledge; no reason to explit or even use this. Listen to @naomik, avoid the arguments object as much as possible.
    – Thomas
    Commented May 7, 2017 at 10:29

3 Answers 3

3

In loose mode, the entries in arguments are linked to the named parameters. So by setting arguments[0], you're setting luke. Literally, the lines arguments[0] = chewie; and luke = chewie; are interchangeable. So later when you use arguments[1] from luke, you're using the updated value (chewie).

Strict mode removes this magic link:

"use strict";
function starWars(luke, darth, han, chewie) {

   arguments[0] = chewie;
   arguments[1] = luke;

   console.log(arguments[0]);
   console.log(arguments[1]);
   console.log(arguments[2]);
   console.log(arguments[3]);
 
} 

starWars("Luke Skywalker", "Darth Vader", "Han Solo", "Chewbacca");

1

You're re-assigning the luke variable with chewie since argument[0] is a reference to luke.

So after arguments[0] = chewie, what happens is luke = chewie.

A workaround could be :

var tempLuke = argument[0];
arguments[0] = chewie;
arguments[1] = tempLuke;
1

When you change arguments object, you also change the argument variables of the function, because it holds references to the variables.

To summarize

1) arguments[0] = chewie;

Here, you also set variable luke to chewie ('chewbacca')

2) arguments[1] = luke;

Here, luke is already became 'chewbacca' in the first step. So, you are making argument dart also 'chewbacca'.

Not the answer you're looking for? Browse other questions tagged or ask your own question.