Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion with JavaScript scoping [duplicate]

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?

like image 381
Haris Bin Zahid Avatar asked Nov 22 '15 09:11

Haris Bin Zahid


3 Answers

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.

like image 173
Thilo Avatar answered Oct 21 '22 21:10

Thilo


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.

like image 43
Stephen Bolton Avatar answered Oct 21 '22 19:10

Stephen Bolton


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/

like image 1
CoderPi Avatar answered Oct 21 '22 20:10

CoderPi