This might be a duplicate but I did not know how to search for it.
Why does
var test = test || {};
work, but
var test = testing || {};
throws an error? At the point of definition both test and testing are undefined.
Edit
The error thrown is “Reference Error: testing is not defined”
There’s a difference between a variable being undefined in the sense of not existing and a variable holding the value
undefined.In your first example you declare
testwithvarsuch that when the expression on the right of the=is evaluated the variabletestexists but has the valueundefined.In your second example you haven’t defined
testingat all, hence the error.EDIT: It occurs to me that perhaps further explanation wouldn’t hurt.
To simplify, the JavaScript engine takes two passes through the code. The first pass is the parse/compile phase, and it is then that variable declarations but not assignments happen. The second pass is the actual execution, and it is then that assignments occur. This results in an effect often called “variable hoisting” – it is as if the JS engine “hoists” the declarations to the top of their scope but still does the assignments in place.
So as to the point of code like this:
…it is basically saying “Does
testalready exist with a truthy value? If so use it, otherwise set it to a new empty object.”The JS engine doesn’t mind if the same variable is declared more than once in the same scope – it basically ignores the second declaration, but doesn’t ignore any assignment included with the second declaration. So if
testis declared in some other script block, perhaps in a separate JS include file, then the line in question just assignstestto itself (assuming it has a truthy value, where all objects are truthy). But if it hasn’t been declared elsewhere it will still exist as a result of the currentvarstatement but it will beundefinedbefore the current assignment so then the||operator returns the right-hand operand, the{}.