2

I understand that all variables are hoisted but the assignments are not ( never mind functions for this question - that makes sense to me - related SO ).

But I don't see how this effects the code. I wrote a fiddle to experiment.

What is the benefit if you hoist the variable and give it the value of undefined which appears to be the case.

var a = 1;

function foo (proxy){
    print(proxy);
}

function print(out){
    document.getElementById("out").innerHTML = out;
}

// foo("you")

print(d); // undefined

var d = 4;

print(d); // 4

https://jsfiddle.net/6ue7052k/1/

Community
  • 1
  • 1
arc.slate .0
  • 428
  • 3
  • 8
  • Remove the `var` before `d` and the first call to print will throw an exception. – Evan Trimboli May 03 '16 at 21:18
  • Why was this question reopened? It's a clear duplicate of [Why does JavaScript hoist variables?](http://stackoverflow.com/questions/15005098/why-does-javascript-hoist-variables) –  May 03 '16 at 21:27
  • 1
    @squint It didn't seem to really be a complete duplicate to me. Why it hoists them is different question from how it affects the code. – Paul May 03 '16 at 21:29
  • @Paulpro: I think he must have meant philosophically, since he knows the runtime effect of making it `undefined`. –  May 03 '16 at 21:33
  • @arc: My opinion, but I'd say that it not only has no benefit, but in fact it is detrimental to an intuitive understanding of what is taking place. The linked answer seems to explain how it came about, and that it's simply a side-effect how the interpreters worked *(which was why I marked it as a duplicate)*. –  May 03 '16 at 21:35

1 Answers1

2

Here's one way it can affect the output:

function outer ( ) {

    var a = 'foo';

    function inner ( ) {
        console.log( a );
        var a = 'bar';
    }

    inner();

};

Without hoisting outer() would output 'foo', but because the local var a declaration is hoisted, it outputs undefined instead. That's not very useful, but it shows that it can have an effect.

There is no benefit to variable hoisting when writing JavaScript. Anything that it achieves could be done just as easily without it, by declaring all your variables at the beginning of each function (without assigning to them). It's just an implementation-detail.

Paul
  • 139,544
  • 27
  • 275
  • 264