0

While coding for simple function declaration, there is a strange behavior by Firefox Scratchpad.

console.log(x);
var x = 0;
var func = function() {
  console.log(y);
  var y = 1;
};
func();

When I executed above code first time with Run, it gave result as below :

undefined undefined

But when I executed it second time, it gave below result :

0 undefined

So I assumed that the value must saved in cache, but then why wasn't the variable y still undefined?

Also when I repeated it with Reload and Run, the first result was repeated.

Tiny Jaguar
  • 433
  • 3
  • 12
  • 30

2 Answers2

1

Its all about var top-hoisting. and function's block scope

When you run the first time your code actually look like this one.

var x;
console.log(x); // undefined as  still x is not defined
x = 0;
var func = function() {
   var y;
  console.log(y); //undefined as still y is not defined
  y = 1;
};
func();

Now,when you re-run second time,status of func() is not going to change as it redefined the block scope of func So at second run

var func = function() {
   var y;
  console.log(y); //undefined as still y is not defined 
                  //as scope is re-initializd 
  y = 1;
};

In javascript,every function when invoked, create a new execution context

but as var x; declared and defined in global scope during first time executiion,it is fetched from there. so, x=0 and y=undefined

RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
0

Since first time when you execute that time there is no x and y variable declared before using it. As soon as it comes to second line x is declared as global which remains in your page scripts. but in case of y variable, it is declared inside the function, its scope limited to function only hence y is not going to be global.

Hence when you refresh your page that time x variable gets that global value but not in case of y. Its all about scope of variable in Javascript

BornToCode
  • 207
  • 2
  • 7