Variables Hoisting in Javascript

Variables have either a local scope or a global scope. Unlike most programming languages, JavaScript does not have block-level scope (variables scoped to surrounding curly brackets); instead, JavaScript has function-level scope. Following are the vital points to be noted in regards with variable hoisting.
  • Variables declared within a function are local variables and are only accessible within that function or by functions inside that function.
  • If a variable is initialized (assigned a value) without first being declared with the var keyword, it is automatically added to the global context and it is thus a global variable.
  • All declarations are hoisted to the top of the function i.e. moved to the top.
  • Only declarations are hoisted, intialisation or assignment are not moved. So, the following function: would be treated as follows after hoisting:
  • Also, same is the case with function assignment: i.e. variable assignment and function assignment is not moved up.
  • function declaration takes precedence over variable declarations.
  • variable assignment takes precedence over function declaration.
Share your insights in the comments below. References: Javascript is sexy