5

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?

suman
  • 195
  • 13
  • although its wrong, you can use `window.val` instead of `val` inside your function, you have to understand that the scope of first `val` is `window` class and the second `val` is in `func()` class – neo Jan 12 '15 at 09:15

2 Answers2

3

The variable val in the following line

var val = 'ple'

is getting hoisted to the top of the function.

The vals(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';
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
0

Javascript has functional scope and not block scope until we get the let statement in ES6...

Sten Muchow
  • 6,623
  • 4
  • 36
  • 46