Understanding the following javascript code

I have javascript that I came across. I do not understand the flow of the code execution process.

var val = 'ap';

function func() {
    if (!val) {
        var val = 'ple';
    }
    console.log(val);
}
func();
console.log(val);

The result, which I thought would be ap, then ap. But I get hello and then ap. How does this happen?

+4
source share
2 answers

Variable valin the next line

var val = 'ple'

rises to the top of the function.

The value of vals (inside the function) is equal undefined, which is false, therefore the condition ifis successful, since it !falseis equal to, trueand therefore, valinside the function is set to 'ple'. It looks something like

function func()
   var val; // val = undefined
   if(!val) {  // it still undefined and !undefined is true
      val = 'ple'; // so this code executes
   }
   console.log(val); // 'ple'
}

, javascript . val

val = 'ple';
+3

Javascript , , let ES6...

0

Source: https://habr.com/ru/post/1570831/


All Articles