Because you declared nw1 using the var keyword within the closure of the function, it has function-wide scope even tho' the declaration falls after the initial reference. The local variable shadows the global one within the scope of the function, and the local variable is undefined locally at the first point you reference it.