0

I'm a Java developer trying to learn JavaScript ethos.

Are these two approaches for creating a static object in JavaScript different in any non-syntactical way? Which approach is more acceptable from a JavaScript programmer's perspective?

Approach A:

var obj = {};
obj.field1 = /* some expression */;
obj.field2 = /* some expression */;

Approach B:

var obj = {
    field1: /* some expression */,
    field2: /* some expression */
};
3
  • 1
    I tend to use Approach B. Approach A is nice when you need to access the object literal. For example, if you wanted to define field2 based on field1; you can't exactly do that in the object literal initialization. Commented Jul 25, 2013 at 14:22
  • Another, similar but different in effect way is to use a new operator on a constructor function: var obj = new (function Object() {this.field1 = /* some expression */; this.field2 = /* some expression */; var privateProperty = "somevalue"; this.field3 = this.field1+privateProperty; })(); This allows you hide some properties if that's required. Commented Jul 25, 2013 at 14:28
  • Another way is to use: Object.create developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jul 25, 2013 at 14:29

1 Answer 1

1

I believe that both of the objects end up being created in a similar manner, and the difference in performance (if any) will be minute to the point where you shouldn't notice a difference.

This is not universal, though. When creating arrays, it is more efficient to use a similar approach to B. This is because (at least with V8) allocating an array with a set size is more efficient because it knows the size of the array.

// Here V8 can see that you want a 4-element array containing numbers:
var a = [1, 2, 3, 4];

// Don't do this:
a = []; // Here V8 knows nothing about the array
for(var i = 1; i <= 4; i++) {
    a.push(i);
}

Source: Smashing Magazine

I would suggest trying out the Chrome Profiling Tools to see if you can notice a difference between the efficiency of both approaches, although I think if there is a difference it will be too small to make a difference.

Further more, if you are new to JavaScript, I would suggest checking out the awesome JavaScript style guide created by AirBnB. There are a ton of great tips for writing efficient and clean JavaScript.

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

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.