thomaux
thomaux

Reputation: 19718

JavaScript performance of || operator to instantiate a variable

Just a quick question that I can't seem to find a reliable source for. I always use the || operator for shorthand undefined checks, like

myVar = myVar || {};

But I'm wondering if this means it will reassign myVar if it exists? And hence if it would be better, from a performance point of view, to expand this to an if statement as such:

if(!myVar) myVar = {};

Many thanks in advance for clearing this up!

Upvotes: 0

Views: 56

Answers (2)

Esailija
Esailija

Reputation: 140220

I cannot imagine that you would run this more than a few times at runtime. It will never be a problem.

If this is in hot function then you are screwed anyway because implicit/optional stuff is intuitively very bad. I cannot imagine you have a hot function that needs to do this. You are probably establishing classes or modules - you could run a loop for 100000 times additionally and not notice anything.

Upvotes: 1

Jaroslav Lipsky
Jaroslav Lipsky

Reputation: 39

How about jsPerf? I cant check it myself (mobile phone) http://jsperf.com/browse

Upvotes: 0

Related Questions