2

I have a problem with a local scope. The second console.log doesn't show "a" value, but shows undefined. Why so?

"use strict"

console.log(a); //undefined 
var a = "a";
function b(){
  console.log(a); // why is undefined here? 
  var a = "a1";
  console.log(a); // here is "a1"
}
b();
alexmac
  • 19,087
  • 7
  • 58
  • 69
Alexey
  • 79
  • 3
  • Remove the second `var` to _assign_ a value to the global `var a` instead of _redeclare_ it. – Lionel T Apr 26 '16 at 08:57
  • var a inside a function is also a global scope..why you declare both.. – nisar Apr 26 '16 at 08:58
  • if your brother and friend are both named "bob", you need to be more specific on a car ride with both. – dandavis Apr 26 '16 at 08:58
  • 2
    Possible duplicate of [Surprised that global variable has undefined value in JavaScript](http://stackoverflow.com/questions/9085839/surprised-that-global-variable-has-undefined-value-in-javascript) – James Thorpe Apr 26 '16 at 08:59

4 Answers4

3

JS will process your code like:

"use strict"

var a; // undefined 
console.log(a); //undefined 

a = "a";

function b(){
  var a; // undefined

  console.log(a); // all is clear, LOCAL variable a is undefined. 

  a = "a1";
  console.log(a); // here is "a1"
}

b();

read more about hoisting here.

Also you can read about Function declaration hoisting, this is an important part of JavaScript fundamentals too.

Andrew Evt
  • 3,613
  • 1
  • 19
  • 35
1

Object-Oriented JavaScript, 2nd Edition: When your JavaScript program execution enters a new function, all the variables declared anywhere in the function are moved (or elevated, or hoisted) to the top of the function. This is an important concept to keep in mind. Further, only the declaration is hoisted, meaning only the presence of the variable is moved to the top. Any assignments stay where they are. In the preceding example, the declaration of the local variable a was hoisted to the top.

var a = 123;

function f() {

    var a; // same as: var a = undefined;

    alert(a); // undefined

    a = 1;

    alert(a); // 1
}
Ali Mamedov
  • 5,116
  • 3
  • 33
  • 47
0

Hoisting is JavaScript's default behavior of moving declarations to the top. You have an a variable in your function scope. This is how it looks like when you're executing it:

"use strict"

console.log(a); //undefined 
var a = "a";
function b(){
  var a;
  console.log(a); // Undefined because a is not set
  a = "a1";
  console.log(a); // here is "a1"
}
b();
Starfish
  • 3,344
  • 1
  • 19
  • 47
0

Because you have another variable a defined in function b, so it' like this:

function b() {
  var a;
  console.log(a);
  a = "a1";
  console.log(a);
}