2

I'm currently learning javascript and I came across this rather odd behavior when setting a property multiple times. For example:

var duck = {feet: 1, feet: 2}

On running

show(duck)

I get

{feet:2}

Is there some weird javascript reason for this behavior? Why is no error thrown?

1
  • In which way is this unexpected? You first tell him that feet is 1 and then that it is 2. He'll only remember the last one. Commented Jun 20, 2013 at 15:11

3 Answers 3

3

You cannot have multiple properties of the same name in an object, but the language lets it pass silently. That's a flaw in the language. ECMAScript 5 strict mode fixed that, so the following will throw an error:

"use strict";
var duck = {feet: 1, feet: 2}
// SyntaxError: Duplicate data property in object literal not allowed in strict mode 
Sign up to request clarification or add additional context in comments.

3 Comments

Is it a flaw, or is it just recognizing a previously set property and overwriting it? Just wondering.
I'm racking my brain to think of a scenario where you'd do this on purpose... all I can think of this code generation, maybe to feed eval. If code existed that was doing this on purpose, it might work but it would be too clever for its own good (too hard for subsequent devs to read the intent of the application)
@SurrealDreams It's both. The flaw is not throwing an error (since duplicate keys in an object literal make no sense).
0

I kind of agree it would make sense to throw an error here. I think that the parser just expands the object declaration into a series of statements, so no part of it is actually invalid.

duck.feet = 1;
duck.feet = 2;

@Blender: I'm guessing show is a method among his libraries that steps through each property and prints it out with its associated value.

Comments

0

Non-strict JavaScript allows objects to contain multiple properties with the same name. When the same name is used multiple times, only the last declaration is used. Strict mode requires that all property names are unique.

"use strict";

Comments

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.