javascript - Are there any instances in which hoisting behavior is beneficial -


i came across topic of hoisting while having casual discussion javascript developers, , told hoisting not mistake, error or poorly written functionality powerful tool developers.

can explain how javascript hoisting of variables , functions serves powerful concept in javascript or how helpful while writing code? (or) unintended concept accidentally got discovered developers?

this favorite article on topic of hoisting , other javascript scope issues/features, , explains better ever hope to:

http://www.adequatelygood.com/javascript-scoping-and-hoisting.html

edit:

i missed asking when hoisting useful , not does.

so, you've read article , know does, here's common snippet makes use of hoisting:

js file:

var myvar = myvar || {}; myvar.foo = function(){}; //etc... 

you'll see used @ top of many oop javascript files declare object. reason can write way because of hoisting in javascript.

without hoisting have write

if(typeof myvar != 'undefined'){ var myvar = myvar; }else{ var myvar = {}; }

or along lines.

another neat trick hoisting allows follows:

var a, b = = "a"; 

this equivalent to:

var = "a"; var b = a; 

another nice thing hoisting happens when write functions.

in more traditional language without hoisting, need write functions @ top of page before code executed. otherwise error function not exist.

with hoisting, functions can declared anywhere (so long use var), , hoisted top, meaning won't errors.

now, if you're writing own code, should declare variables @ top of respective scope anyway, let's have couple script files you're trying concatenate in one. hoisting makes process more simple.


Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -