0

I am a beginner for javascript, and I encountered something weird when I was trying to understand variable-scope. here is the code I wrote:

var year = 2020

function someFunction(){
    console.log(year) 
}
someFunction()
and the output was: 2020

but then I redeclared the variable "year" again inside the function but after the console.log() statement like this :

var year = 2020

function someFunction(){
    
    console.log(year) 
    var year = 1999
}
someFunction()

and the output I got was: undefined

As a beginner, I found this hard to understand why . I hope you can help me. Thanks!

Bereket
  • 1
  • 1
  • In your second case, the inner `year` *declaration* will be hoisted to the top of the function, but it's *value assignment* stays where it is, so until the code reaches that point, the value of the variable is `undefined`. – CRice May 29 '20 at 16:56
  • For what it's worth, these are the kind of counter-intuitive error-prone behaviours that recent ECMAScript revisions have been addressing (namely `let` and `const`). – Álvaro González May 29 '20 at 17:00
  • So the function takes and prints out the global variable **year** if there is no other inner declaration by the same variable name? – Bereket May 29 '20 at 17:02
  • Yes, this is why it is often said not to [shadow your variables](https://en.wikipedia.org/wiki/Variable_shadowing). – CRice May 29 '20 at 17:04
  • I get it now. Thank you so much! – Bereket May 29 '20 at 17:08
  • Please check the duplicate links in the blue box at the top. – adiga May 29 '20 at 17:36
  • Thank you so much! the second link has resolved another question I had in mind. – Bereket May 29 '20 at 18:26

0 Answers0