To actually answer your question of WHY this is happening, it is because of variable hoisting.
Basically, there is a phase before executing code in the global scope or inside a function where the code is scanned for all var
and function
declarations (not to be confused with function expressions, but that's a different story).
All these variable and functions are then declared inside the current scope, and only afterwards does the code actually run.
This happens regardless of their position in the code, with scopes corresponding to function bodies, not blocks of statements. And what makes this even more counter-intuitive, even if you set an initial value to variables in their declarations, they will still remain "empty" until the declaration is reached again in normal execution flow.
So when you write:
if(!embed_BackgroundColor) {
var embed_BackgroundColor;
embed_BackgroundColor = "#F4F4F4";
}
what actually happens is this:
Code is scanned for var
declarations. embed_BackgroundColor
is declared inside this scope, regardless of whether it was already declared or not. Its initial value is undefined.
Execution of the code begins. The if
statement is run. The variable is declared, but its value is undefined, so the condition is true. Using typeof
wouldn't help you distinguish here between an undeclared and a declared-but-not-yet-set variable. It makes no difference anyway.
The var
declaration is reached by normal flow of the code. If you had given the variable an initial value it would have been set now. In this case nothing happens.
embed_BackgroundColor
is set to the value "#F4F4F4"
.
So, bottom-line is: you can use typeof variable == 'undefined'
as seen in the other answers, or even plain '!variable' as you were initially using, but don't use var
or that will ruin everything.