Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusing behavior on function scope

I am new to javascript and while I was practicing scope I tried the following code:

var il = "inner";
var o ="outer";

var of = function(){

  console.log(o + " " + il);

  o = "baher";
  var il = "ander";
  console.log(o + " " + il);

  var lf = function(){
    console.log(o  + " " +il);
    o = "mazed baher";
    var il = "mazed ander";
    console.log(o + " " +il);
  };

  console.log(o + " " +il);

};

of();
console.log(o + " " + il);

////////////////////////////////////// Its output is amazing

"outer undefined" 
"baher ander" 
"baher ander" 
"baher inner" 

I cannot understand this code. I used console.log 6 times and only got four outputs. And why is "il" is undefined on the first log?

like image 849
bawa g Avatar asked Mar 09 '26 09:03

bawa g


2 Answers

it only giving output four times

Two of your console.log statements are inside the lf function, which you never call.

why "il" giving undefined first time

var statements are hoisted.

var of = function(){
    console.log(o + " " + il);
    o = "baher";
    var il = "ander";

The last line in this section creates a local variable il in the scope of the function. Since it is hoisted, this happens as soon as the function is entered.

The second line reads the value of that local variable, but it hasn't been assigned a value yet so it is undefined.

The third line then assigns a value to it.

like image 128
Quentin Avatar answered Mar 11 '26 09:03

Quentin


Firstly, new scope is created only for functions. condition blocks like while and if do not create new scope.

Secondly, variable definitions in JS will always be lifted on top of scope. So, when you create variable via var it will be actually defined on top of scope and initialized as undefined.

console.log(o + " " + il);
o = "baher";
var il = "ander";

In given sample, local il will override il from outer scope. So, it will look like this:

var il; // undefined
console.log(o + " " + il);
o = "baher"; // outer scope
il = "ander"; // inner scope
like image 45
Unrealsolver Avatar answered Mar 11 '26 08:03

Unrealsolver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!