0

I'm asked by an interviewer, is there a difference between the following code:

var o1 = {
    a: 1,
    b: 2,
    c: 3
}

for( var p in o1) {
    // ...
}

vs

var o2 = new Object()
o2.a = 1;
o2.b = 2;
o2.c = 3;

for( var p in o2) {
   // ...
}

I can't think of any difference, is there any??

Aaron Shen
  • 8,124
  • 10
  • 44
  • 86
  • I would tentatively say no... I could be wrong. – Mitya May 19 '16 at 10:40
  • No difference, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects – Tobias Beuving May 19 '16 at 10:41
  • I would also say no. But it may differ at runtime (thinking about which side of the `=`-sign the different things are). – Arg0n May 19 '16 at 10:43
  • Possible duplicate of [What is the difference between \`new Object()\` and object literal notation?](http://stackoverflow.com/questions/4597926/what-is-the-difference-between-new-object-and-object-literal-notation) – Rayon May 19 '16 at 11:09

1 Answers1

1

Assuming that the semi-colon missing from the new Object() line is unintentional, then there is no difference...

http://www.w3schools.com/js/js_object_definition.asp

...except that the first one — according to this comment — executes faster.

The two examples above do exactly the same. There is no need to use new Object(). For simplicity, readability and execution speed, use the first one (the object literal method).

MichaelK
  • 2,859
  • 1
  • 14
  • 16
  • @Rayon ...because... why exactly? – MichaelK May 19 '16 at 10:57
  • So no actual reason other than that someone on SE generally don't like them and justifies with using the same kind of vague and unspecified arguments they accuse W3 schools for. – MichaelK May 19 '16 at 11:02
  • Then post an answer referencing that instead of wasting our time with these comments. Are you here to help or just go "That's no good"? – MichaelK May 19 '16 at 11:05
  • If _"That's no good"_ will improve the quality of the answer and will help the future users then _"YES"_, I am am here for that... – Rayon May 19 '16 at 11:07
  • It does not. It just negs an answer without any kind of guidance to a better alternative, it antagonizes and annoys, it does not help. – MichaelK May 19 '16 at 11:10
  • [__MDN__](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects) is definitely better alternative than _your_ _w3schoold_ – Rayon May 19 '16 at 11:15
  • Then post an **answer** with that reference instead and stop using up our time with these non-substantiated "It's worse/better, because I say it is" statements. – MichaelK May 19 '16 at 11:18