简体   繁体   中英

Javascript Memory Savings - if Statement var Declarations

Do variables get initialized / stored in memory if they reside in an if statement which doesn't execute, as in the following:

function blah(){
    if(something === true){
        var blahOne = 1;
        var blahTwo = 2;
        var blahThree = 3;
    } else {
        console.log('The above if statement usually won\'t execute');
    }
}

My assumption is no, but Javascript can be a quirky language to say the least. Thanks in advance for your help!

All var declarations are moved to the top of the function and initialized to undefined. That is called variable hoisting. JavaScript doesn't have block scope, only function and global scope.

Your code is equivalent to the following

function blah(){
    var blahOne, blahTwo, blahTree;
    if(something === true){
        blahOne = 1;
        blahTwo = 2;
        blahThree = 3;
    } else {
        // blahOne, blahTwo, blahThree are set to undefined
        console.log('The above if statement usually won\'t execute');
        // But since they have been declared, there's no error in reading them
        console.log(blahOne, blahTwo, blahThree);
    }
}

There is no thing like a block scope in Javascript. See this article . if you want to say so: Javascript has function-scope. So the answer to your question is yes they get initialized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM