0

What is the difference in performance and reliability of the following variable assignments:

var obj = {name: "Antonia"};

var foo = obj.name ? obj.name : "foo";
var baz = obj.name || "baz";

Since obj.name is defined, both foo and baz will contain "Antonia".

As far as I know, the code should behave the same for obj.name values other than null, undefined, 0 and false. If the property is set to one of those values foo will contain "foo" and baz is assigned "baz".

Is there some kind of drawback I'm missing? Which one do you recommend to use?

Thanks!

PS: fiddle to play aroud https://jsfiddle.net/a2rgvhzm/

Elias Rabl
  • 317
  • 4
  • 13
  • 2
    I think that at this point, it is only about personal preference... – Karl-André Gagnon Sep 11 '17 at 14:34
  • I agree with @Karl-AndréGagnon, the or version is more clear to me anyway – Vitaliy Terziev Sep 11 '17 at 14:36
  • You should also clarify what you're asking. It sounds like you might be asking about the canonical use - in which case, there really isn't any. It's whatever is clearer in your codebse – Sua Morales Sep 11 '17 at 14:39
  • See here for checking undefined variables: https://stackoverflow.com/questions/27509/detecting-an-undefined-object-property – ceving Sep 11 '17 at 14:40
  • Also note that in es6, there can be better ways to assign default variable: https://jsfiddle.net/a2rgvhzm/1/. Not to forget that functions can have defaults too (`function( foo = true ){}`). – Karl-André Gagnon Sep 11 '17 at 14:40

1 Answers1

2

The example you gave albeit, awkwardly achieves the same thing. So yeah, they're equivalent in this case.

var foo = obj.name ? obj.name : "foo";

This is awkward because you're asking whether you have the object.name which is typically answered with true/false. Here you're answering the question with the member itself or a random string. So the question/answer isn't consistent.

var baz = obj.name || "baz"; I've seen this as more widely used in Production, which is more declarative. Instead of asking a question you're saying, "Assign baz with the object name, oh, and in case it doesn't exist then assign baz with the string "baz", which we know exists for sure."

You might want to profile each of these to answer your q about performance. I hope this clarifies your question about best practices.

Sua Morales
  • 894
  • 10
  • 21