1

Why is the x variable in the example below returning undefined rather than 25?

var x = 25;

(function() {
  console.log(x);
  var x = 10;
})();
j08691
  • 204,283
  • 31
  • 260
  • 272
darksoulsong
  • 13,988
  • 14
  • 47
  • 90

2 Answers2

5

This is common problem of hoisting in javascript.The code actually looks like this.The value is assigned after the console.log.

The second undefined(if run on developer's tool) is because the function is not explicitly returning anything

This is how Javascript actually executes your code due to var hoisting:

var x = 25;

(function() {
  var x;
  console.log(x);
  x = 10;
})();
brk
  • 48,835
  • 10
  • 56
  • 78
0

It's Self-Invoking Functions that will invoke without calling from specific function or place. and your declared x inside that function and preparing for running that function make javascript ignore global variable x and try to create local x.if you remove var x = 10; from the function inside then everything will be OK:

var x = 25;

(function() {
  console.log(x);
})();
Yashar Aliabbasi
  • 2,663
  • 1
  • 23
  • 35