0

I was reimplementing a memoize function using the Arguments object. I am wondering why this would work. For example, passing in 2 arguments:

var args = Array.prototype.slice.call(arguments); // input: 1,2

Then I would store the args array into an object. For Example,

var obj = {};
    obj[args] = 2;

If you were to call Object, you would see this as:

{ 1,2: 2 }/*shows as this*/  { [1,2]: 2 }/*but not as this*/

Not that I wanted the second object, just curious what is happening under the hood. Is this what you call Javascript coercion?

4
  • All property names are strings, so args is getting converted to a string, yes. Commented Jan 5, 2016 at 21:54
  • Using an array as an object property name won't really work very well. The array will be converted to a string first, and that result will be the actual name of the property. Commented Jan 5, 2016 at 21:54
  • Converting an array to a string works by doing array.join(",") Commented Jan 5, 2016 at 21:55
  • Ah, I see! Thanks you very much for the information. I wasn't sure what was happening, learning something new everyday! Commented Jan 5, 2016 at 21:57

1 Answer 1

1

Object property names are always strings. So when you do:

obj[args] = 2;

it treats this as

obj[args.toString()] = 2;

And the toString() method of arrays is equivalent to .join(","), so the above is equivalent to:

obj[args.join(",")] = 2;

which matches the result you saw.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, it makes a lot of sense! I was scratching my head for awhile lol.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.