I was looking through the code of a JS library and saw this pattern:
function module() {
function func() {
//...
definedAfter();
//...
}
return func;
var x = "....";
function definedAfter() {
//...
console.log(x); //outputs undefined
//...
}
}
Google's Closure compiler flags the variable x
as unused code, which seems reasonable, but the interesting part is that the variable is declared but with a value of undefined
(due to hoisting).
Is this a bug in the library? Or is there some subtle behavior that is being exploited here? Maybe some type of optimization? Do different browsers act differently with regard to this example?
EDIT: I'm curious about the intent (bug or otherwise) of the original code, since it seems like x
would always be undefined
.