arc.slate .0
arc.slate .0

Reputation: 428

What is the significance of variable hoisting?

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/

Upvotes: 2

Views: 167

Answers (1)

Paul
Paul

Reputation: 141857

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.

Upvotes: 2

Related Questions