I have following javascript that I came across. I don't understand the process flow of the code execution.
var val = 'ap';
function func() {
if (!val) {
var val = 'ple';
}
console.log(val);
}
func();
console.log(val);
The output that I thought would be was, 'ap' then 'ap'. But I get 'ple' and then 'ap'. How is this happening?
The variable val
in the following line
var val = 'ple'
is getting hoisted to the top of the function.
The val
s(inside the function) value is undefined
which is falsey that is why the if
condition is successful because !false
is true
and hence the val
inside the function gets set to 'ple'
. It looks roughly like
function func()
var val; // val = undefined
if(!val) { // it's still undefined and !undefined is true
val = 'ple'; // so this code executes
}
console.log(val); // 'ple'
}
Remember that scope in javascript isn't block scope. Instead what you've to do is set the already declared val
val = 'ple';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With