1

Which if the following two methods is the best / most practical to use?

var arr = (new function (){
    this.Foo = "Foo";
    this.Bar = "Bar";
});

OR

var arr = new Array (
    Foo = "Foo",
    Bar = "Bar"
)

I understand that both of the above can have properties added to them, Please note there is currently no application of the above code so no context around the question, but which is more preferred? Thanks

3
  • 3
    The first code fragment defines a constructor for a "class" with "properties" Foo and Bar and then immediately instantiates it. The second code fragment creates an array with elements "Foo" and "Bar" (and in the process creates two new global variables Foo and Bar). Whether you want an object with two properties, or an array with two elements, is up to you. Commented Aug 11, 2016 at 14:26
  • If you wish to put that as an answer i would be happyto accept :) Commented Aug 11, 2016 at 14:29
  • You should avoid the second method, because it not do what you expect it should do, and it is dangerous as it create global variables. if you need objects use object literals, instead. Commented Aug 11, 2016 at 14:31

2 Answers 2

1

The first code fragment defines a constructor for an object with properties named Foo and Bar, and then immediately instantiates it with new.

The second code fragment creates an array with elements "Foo" and "Bar" (and in the process creates two new global variables Foo and Bar, which you probably don't want).

Whether you want an object with two properties, or an array with two elements, is up to you.

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

Comments

0

Both are really bad. First equals just var arr = {Foo: "Foo", Bar: "Bar"}

In second you create array, but when you do Foo = "Foo" inside you actually declare global var Foo, because Foo = "Foo" is an expression that returns "Foo" for array element.

2 Comments

They're not "equal" in the first case, e.g. constructor property is different. I'm sure there's deeper differences.
@djechlin yes, but case where you use this arr.constructor is very wierd. There are some little differences, but code not going to be good with them.

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.