Reputation: 14429
Can someone explain why undefined is printed to the console and not 4?
var a = 4;
function test() {
if (!a) {
a = 3;
}
console.log(a)
}
undefined
Upvotes: 0
Views: 42
Reputation: 87203
This has nothing to do with variable hoisting
.
Because you haven't return
anything. So, when you execute this code in browser console, it show undefined
.
To get 4
, as result you need to call the test
function and return a
from the function.
Code:
var a = 4;
function test() {
if (!a) {
a = 3;
}
console.log(a);
// Return a from the function, if needed
return a;
}
// Call function here
test();
Upvotes: 1