4

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()}`)
Liam
  • 27,717
  • 28
  • 128
  • 190
  • You have two `lang2` variables, one in the function and one outside. Remove the `var` from `var lang2 = lang1` and you'll see it do what you expect – Liam Apr 28 '21 at 08:18
  • 3
    Also don't listen to people who tell you not to put `;` [they're wrong.](https://stackoverflow.com/a/444082/542251) – Liam Apr 28 '21 at 08:20
  • What have you tried to resolve the problem? – Nico Haase Apr 28 '21 at 08:23
  • I'd also recommend you start using `let` and `const` instead of `var`. [It has much more predictable behaviour](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var) – Liam Apr 28 '21 at 08:26
  • 1
    *"But `var` is function scoped. For this reason it is hoisted to top and saw that it's defined."* exactly. Variables declared with `var` are visible *everywhere* in the function. You described exactly how `var` works but expected a different outcome. What did you expect to happen when a variable declaration is hoisted? Which value did you expect `lang2` to have in the `if` condition? – Felix Kling Apr 28 '21 at 08:28
  • Just remove all `var` in your case to get your desirable outcome. Make everything global: https://stackoverflow.com/a/64216485/188331, and suggested to add the trailing `;` in every line. – Raptor Apr 28 '21 at 08:28
  • Also you are contradicting yourself in your question. First you say you are expecting it to print `Java`, then you say you expect it to print `JavaScript`. – Felix Kling Apr 28 '21 at 08:51

1 Answers1

6

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
}
Ahmad
  • 12,336
  • 6
  • 48
  • 88
  • Thank You. It's happened because lang2 isn't defined on locally (que. code). so that the condition is true. That's why Java is printed. – Md. Maruf Sarker Apr 28 '21 at 08:38