Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of variables (Hoisting) in Javascript

One of my friends was taking an online quiz and he asked me this question which I could not answer.

var global = false;

function test() {
  global = true;
  return false;
  function global() {}
}

console.log(global); // says false (As expected)
test();
console.log(global); // says false (Unexpected: should be true)

If we assume that functions are hoisted at the top along with var variables, let's try this one.

var foo = 1;
function bar() {
    return foo;
    foo = 10;
    function foo() {}
    var foo = 11;
}

bar();
console.log(foo); //says 1 (But should be 11) Why 1 this time ??

Here is a JSBin Demo and JSBIN Demo2 to play with.

PS: If we remove function global() {} from test(), then it runs fine. Can somebody help me understand why is this happening ?

like image 959
Sachin Avatar asked Feb 06 '14 17:02

Sachin


People also ask

Which variables are hoisted in JavaScript?

Variables defined with let and const are hoisted to the top of the block, but not initialized. Meaning: The block of code is aware of the variable, but it cannot be used until it has been declared. Using a let variable before it is declared will result in a ReferenceError .

What is the scope of a variable in JavaScript?

The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes. Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code.

Does hoisting work with all the variables?

In JavaScript, hoisting is only done for variable and function declarations but not assignments. So, when a variable is assigned then hoisting doesn't work and gives a TypeError or a ReferenceError.

What is hoisting scope and closure in JavaScript?

Specifically, we discussed how hoisting allows you to refer to JavaScript variables and functions prior to their declaration, and how closures allow you to access function-scoped variables outside of that specific function.


1 Answers

var statements and function declaration statements are "hoisted" to the top of their enclosing scope.
Therefore, the function global(){} in your function creates a local global name.

Assigning to global inside your functions binds to this local name. Here's how you can "rewrite" it using hoisting to understand how the compiler sees it:

function test() {
    var global = function() {};   // hoisted; 'global' now local
    global = true;
    return false;
}
like image 77
SLaks Avatar answered Sep 22 '22 01:09

SLaks