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()
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!
yeardeclaration 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 isundefined.letandconst).