let x = '1'
function first(){
console.log(x)
}
x='2'
function second(){
let x='3'
first()
}
second()
My question is , why is the answer '2' instead of '3'? I know let is block scope and var is function scope,but I just do not get this right. Please help me here, many thx!
You are assigning 3 to a local variable, it only has an effect inside the second function
This example works:
let x = '1'
function first(){
console.log(x)
}
x='2'
function second(){
x='3'
first()
}
second()
initially the function first has no idea what x is about. so it automatically searched in the upper scope.
gladly, on the global scope there is x definition.
Therefore, as this script got initialized, the function console.log in function first reserve the memory address of x, and watches that global variable all along.
This is because of shadowing.
In JavaScript, variables with the same name can be specified at multiple layers of nested scope. In such a situation, local variables gain priority over global variables. If you declare a local variable and a global variable with the same name, the local variable will take precedence when you use it inside a function or block.
And in your case, there is no local variable define inside your first() function so it will take the value of x = 2 of the global variable.
let x = '1'
function first() {
console.log(x)
}
x = '2'
function second() {
let x = '3'
first()
}
second()
See the below code, If you've declared x=4 inside first() then it will return the value 4 instead of 2
let x = '1'
function first() {
x = '4'
console.log(x)
}
x = '2'
function second() {
let x = '3'
first()
}
second()
Check out this if you want to know more about JavaScript Variable Scope and Hoisting: https://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/