Reputation: 101
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
Reputation: 9356
What happens internally when you do var sum=sum||5;
is this:
sum
is defined, it's created, sum
is assigned an undefined
valuesum
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