Definition
According to W3schools ,
In JavaScript, a variable can be declared after it has been used. In other words; a variable can be used before it has been declared. So,Hoisting is JavaScript’s default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).
Code Example
curValue = 5; // Assign 5 to curValue
alert(curValue);//Display 5
var curValue; // Declare curValue
alert(curValue);//Display 5
Negative Impact
So why is this important, there are possibilities of consequences for programmer ignoring this understanding.
Some of it based on my understandings are as below…
var x = 5; // Initialize x
alert( "x is " + x + " and y is " + y ); //alerts x is 5,y is undefined
var y = 7; // Initialize y
var x = 5; // Initialize x
var y = 7; // Initialize y
alert( "x is " + x + " and y is " + y ); //alerts x is 5,y 7
We assume, when we declared and initialize in same line, the effect will take place. In usual case declaration, yes. In hoisting , NO. That is why value alerted above will be different.
Looking at this simple code,we may be able analyze quickly but imagine in production level, if the code is alot, tracing is time consuming. There are probably other cases too.
So how as programmers we can avoid this?
Apply “use strict” in javascript to ensure practice of always declaring variable at the top.
Alternative is to use jslint,jshint and likewise plugin js checker to ensure good js practice.
Benefit
Next question is probably what is the benefit of hoisting feature in javascript?
To me, it can be more forgiving when forget defined a variable when code test without stringent quality code requirement.
Other than that, maybe we have a grouping sequence of code position, having hoisting can help organize.
For instance,
//...all logic processing and functions above here, need invoke curValue
function doSomeMagic(_value){
curValue=1+3+_value;//formula here
}
//declare all at bottom
var curValue;
Furthermore,it plays some role in scoping dynamic vs lexical.
Leave a Reply