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!

7
  • 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. Commented May 29, 2020 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). Commented May 29, 2020 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? Commented May 29, 2020 at 17:02
  • Yes, this is why it is often said not to shadow your variables. Commented May 29, 2020 at 17:04
  • I get it now. Thank you so much! Commented May 29, 2020 at 17:08

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.