Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding following javascript code [duplicate]

Tags:

javascript

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?

like image 632
suman Avatar asked Oct 19 '22 19:10

suman


1 Answers

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';
like image 180
Amit Joki Avatar answered Oct 23 '22 19:10

Amit Joki