I get a strange behavior when declaring an object with the logical OR.
my_var = my_var || {}; // throws TypeError
If I add the var keyword
var my_var = my_var || {}; // returns empty object
Why is this? I can’t seem to find an explanation. my_var is global scope, so why is var changing the behavior?
The first example tries to assign to a property on the global object named
my_varby reading the value from an identifier calledmy_var(OR an empty object). However, the identifiermy_varis not defined at that point, so it fails.In the second example, due to how javascript variable hoisting works, the
my_varvariable is already declared, when you read from it by assign to it.Also have a look at this example:
With var keyword it will work!
This is because variable hoisting will turn it into this: