Вопрос

I came across the topic of Hoisting while having some casual discussion with JavaScript developers, and I am told that Hoisting is NOT a mistake, error or poorly written functionality but a powerful tool for developers.

Can anyone explain how JavaScript hoisting of variables and functions serves as a powerful concept in JavaScript or how is it helpful while writing code? (or) is it just an unintended concept which accidentally got discovered by developers?

Это было полезно?

Решение

This is my favorite article on the topic of hoisting and other JavaScript scope issues/features, and explains it all better than I could ever hope to:

http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

EDIT:

I missed that you were actually asking when hoisting is useful and not just what it does.

So, now that you've read that article and know what it does, here's a very common snippet that makes use of hoisting:

JS File:

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

You'll see this used at the top of many OOP JavaScript files to declare the object. The reason that we can write it this way is because of hoisting in Javascript.

Without hoisting we would have to write

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

or something along those lines.

Another neat trick hoisting allows is as follows:

var a, b = a = "A";

This is equivalent to:

var a = "A";
var b = a;

Another nice thing about hoisting happens when you write functions.

In a more traditional language without hoisting, you need to write all your functions at the top of the page before any code is executed. Otherwise you will get an error that the function does not exist.

With hoisting, your functions can be declared anywhere (so long as you use var), and they will be hoisted up to the top, meaning you won't get those errors.

Now, if you're writing your own code, then you should declare your variables at the top of their respective scope anyway, but let's say you have a couple script files that you're trying to concatenate in to one. Hoisting makes that process much more simple.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top