Why is my function scoped variable not getting set as I expect it to be?

Viewed 47

In this code the I expect it to print I love Java. But var is function scoped. For this reason it is hoisted to top and saw that it's defined. So I'd expect the answer to be JavaScript but wit outputs Java, why?

var lang1 = 'Java'
var lang2 = 'JavaScript'

function getLanguage(){
    if(!lang2){
        var lang2 = lang1
    }
    return lang2
}

console.log(`I love ${getLanguage()}`)

1 Answers

because of Javascript variable hoisting, the code:

function getLanguage(){
    if(!lang2){
        var lang2 = lang1
    }
    return lang2
}

will be rendered to / re-written (if you will) to:

function getLanguage(){
    var lang2;    // undefined local var
    if(!lang2){   // this expression will evaluate to true because !undefined = true
              
        lang2 = lang1   // set the local var to the global lang1
    }
    return lang2        // return the local var
}
Related