In this situation
function test (){
var a = 2
if(a){
var b = 3
}else{
}
console.log(b);
}
test()
test function return 3, even without a return statement
while in another case , return error
function test(){
var a = 2
function test_2 (){
var b = 3
}
console.log(b)
}
test()
this function return error.
3
Answers
The difference is variable scoping and hoisting between the two examples.
In the second example, the variable b is declared inside a nested function test_2. In this case, b is scoped to the test_2 function and is not accessible outside of it.
To fix the second example and avoid the error, you can return the value of b from the test_2 function and then use it in the test function:
Like this:
It’s beacuse if statement accepts all numbers as true except 0.İf statment only sees 0 as false statement.
In your first situtation if(2) means if(true) so b defines as 3.
In your second situation:
-Firstly a variable defines as 2
-Then you try to print b
But b didn’t defined yet cause it is defined inside a test_2 so b variable is not defined for test function that’s why you have an error. Even you try to call test_2 function before printing it won’t display cause b variable only and only recognized in test_2 function. If you want to print the b variable it must defined in test function.Beacuse test_2 funciton is inside the test function.
So if you want the run second usage without error.You can use code like below.
var
variables are function-scoped, so the expectation that avar
variable should not be known outside its functional scope is correct.The mistake in your reasoning is that you think that
if
andelse
are functions and consequently you think that avar
variable created in anif
orelse
block should not be seen outside them.But
if
andelse
are not functions.if
andelse
are conditional statements, so they are not functions.test
in your code is a function. Let me illustrate this for you:First, we check whether the
var
, thelet
and theconst
are seen inside their block’s scope, then we check for the same inside their function’s scope, but outside their block’s scope and finally we do the same check outside their function’s scope.You might also want to check this article‘s Block Scope section.