What happens if a JavaScript variable is re-initialized? -


i'm new javascript , i'm not sure if there called re-initialization in javascript, please excuse if there no such concept.

what happens if javascript variable re-initialized? ex:

function foo() { var x = 10; .... //do .... //do .... //do var x = 20; console.log("x: " + x); } 

what value of x here?

x 20. var "hoisted" (more below), means variable gets declared of beginning of function, before step-by-step code run. initializer on var statement assignment statement.

so code:

function foo() {     var x = 10;     //do     var x = 20;     console.log("x: " + x); } 

is treated though this:

function foo() {     var x;      x = 10;     //do     x = 20;     console.log("x: " + x); } 

when call function, javascript engine several things before starts executing step-by-step code in question. 1 of things through code , process var statements. (although it's called var statement, var more of declaration.)

it's quite fun, code written way:

function foo() {     x = 10;     //do     x = 20;     console.log("x: " + x);      return;      var x; } 

it still valid, , same thing.

more (on blog): poor, misunderstood var

es6 introduce let, behaves differently (amongst other things, scoped block it's in, whereas var scoped function whole if declared within block); details on mdn.


Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -