19

I have a fair bit of understanding about JavaScript scoping -- that the language has function-level scope and the variable and function declarations are hoisted to the top of their containing scope. However, I can't figure out why the following two pieces of code log different values:

This logs the value 1 to the console:

var a = 1;
function b() {
    a = 10;
    return;
    function a() {}
}
b();
console.log(a);

And mysteriously, this logs 10:

var a = 1;
function b() {
    a = 10;
    return;        
}
b();
console.log(a);

So what's going on underneath the hood?

Haris Bin Zahid
  • 235
  • 1
  • 8

4 Answers4

15

I find the first example more mysterious...

In the second example, you do not declare a variable a inside of the function. So when you assign to a, it targets the a on the outside. Pretty straight-forward.

In the first example, you declare a variable a inside of the function, but in an unusual way: By declaring a function called a. So assigning to a will use that local "variable".

Two things to take away here:

a) Variable and function declarations are "hoisted" to the top of their scope. While function a(){} is written near the end, the variable a to hold it is already created and visible at the top of the scope.

b) Functions can be used as variables as well. You can pass functions around, you can re-assign function definitions. They share the same namespace with other variables.

Thilo
  • 257,207
  • 101
  • 511
  • 656
2

Its because when you use a declared function it is hoisted up and turned into a function expression, ie var a = function() {}; This is creating a clash with your a variable.

Jonatas Walker
  • 13,583
  • 5
  • 53
  • 82
Stephen Bolton
  • 365
  • 2
  • 10
1

You can use Visual-Studio for coding:

enter image description here

Programming the code in a TypeScript-File will enable you to see the variable Types by hovering the variable.

enter image description here

It will also warn you, when you try to apply the numerical-value 10 to the variable "a", that was first declared to be a function. That's what I love about TypeScript, you can get more Information about it here: http://www.typescriptlang.org/

CoderPi
  • 12,985
  • 4
  • 34
  • 62
0

JavaScript is interpreter based. Javascript {block} doesn't have a scope, but function have.

In your example,

var a = 1;
function b() {
    a = 10;
    return;
    function a() {}
}
b();
console.log(a);

first, you assign a to be integer 10, but in the end you reassign your a as a function that will be disappear at end of scope.

In this code,

var a = 1;
function b() {
    a = 10;
    return;
    function foo() {}
}
b();
console.log(a);

your a not replaced, and returned to global scope, it'll log 10.

ibrohimislam
  • 717
  • 7
  • 21