JMo
JMo

Reputation: 101

Using short circuit evaluation to define variable

Why do you have to use the var keyword when defining a variable using short circuit evaluation?

This works...

var sum=sum||5;
console.log(sum); //shows 5;

This does not work...

sum=sum||5;
console.log(sum); //error sum is not defined;

Shouldn't the second example just make sum===5 but at the global scope and not the local?

Upvotes: 1

Views: 219

Answers (1)

Dimitris Karagiannis
Dimitris Karagiannis

Reputation: 9356

What happens internally when you do var sum=sum||5; is this:

  • variable sum is defined, it's created,
  • variable sum is assigned an undefined value
  • variable sum is assigned the result of sum || 5, which is like saying undefined || 5, which is 5

When you simply do sum = sum||5 the first and second steps from above do not happen, so in the third step you are short-circuiting something that does not exist at all with the value 5, and that's why you get that error.

In order to understand that better, do this: Open up your browser's console and simply write sum. You will get an error because sum does not exist. Now, do sum = ''. What happened here is that a variable sum was defined/created, as if you had done var sum, it now exists, and it was assigned the value ''.

The essence of the above, which you should understand, is that there is a difference between short-circuiting the value undefined with the value 5 and short-circuiting something that does not exist with value 5

Upvotes: 1

Related Questions