Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is x undefined in inner scope? [duplicate]

Tags:

javascript

In the code below

var x = 1;

(function () {
  console.log(x);
  var x = 2;
}());

Why is it that when console.log(x), x is undefined?

like image 809
Chris Hansen Avatar asked Oct 14 '15 19:10

Chris Hansen


People also ask

Why does console print undefined?

This is because console. log() does not return a value (i.e. returns undefined). The result of whatever you entered to the console is first printed to the console, then a bit later the message from console. log reaches the console and is printed as well.

Why getting undefined value in JavaScript?

A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .

Why is my array undefined?

You get undefined when you try to access the array value at index 0, but it's not that the value undefined is stored at index 0, it's that the default behavior in JavaScript is to return undefined if you try to access the value of an object for a key that does not exist.

What does it mean when something is not defined in JavaScript?

The JavaScript exception "variable is not defined" occurs when there is a non-existent variable referenced somewhere.


2 Answers

Variable hoisting. The actual code is executed like this.

var x = 1;
(function() {
    var x; // x = undefined
    console.log(x);
    x = 2;
})();

Edit: On Mr Lister's advice, a bit on variable hoisting. From MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var):

"Variable declarations, wherever they occur, are processed before any code is executed. The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global."

like image 144
TbWill4321 Avatar answered Oct 05 '22 12:10

TbWill4321


Because of the compiler, even if you initiate a var down below the code, the compiler send it to the top, just like var x;, so it first initiate as undefined "x" before running console.log, that's why is such a good practice to initate all vars you're going to use first thing in the function, so these mistakes won't happen.

like image 24
Kriggs Avatar answered Oct 05 '22 12:10

Kriggs