javascript variable scope in the IF statement

后端 未结 5 1954
粉色の甜心
粉色の甜心 2020-11-30 23:53

Are variables declared and assigned in an \"if\" statement visible only within that \"if\" block or within the whole function?

Am I doing this right in the followin

5条回答
  •  萌比男神i
    2020-12-01 00:44

    JavaScript has no "block scope", it only has function scope - so variables declared inside an if statement (or any conditional block) are "hoisted" to the outer scope.

    if(true) {
        var foo = "bar";
    }
    alert(foo); // "bar"
    

    This actually paints a clearer picture (and comes up in interviews, from experience :)

    var foo = "test";
    if(true) {
        alert(foo); // Interviewer: "What does this alert?" Answer: "test"
        var foo = "bar";
    }
    alert(foo); // "bar" Interviewer: Why is that? Answer: Because JavaScript does not have block scope
    

    Function scope, in JavaScript, typically refers to closures.

    var bar = "heheheh";
    var blah = (function() {
        var foo = "hello";
        alert(bar); // "heheheh"
        alert(foo); // "hello" (obviously)
    });
    
    blah(); // "heheheh", "hello"
    alert(foo); // undefined, no alert
    

    The inner scope of the function has access to the environment in which it is contained, but not the other way around.

    To answer your second question, optimisation can be achieved by initially constructing a 'minimal' object which satisfies all conditions and then augmenting or modifying it based on particular condition(s) which has/have been satisfied.

提交回复
热议问题