Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function scoping and hoisting

I just read a great article about JavaScript Scoping and Hoisting by Ben Cherry in which he gives the following example:

var a = 1;  function b() {     a = 10;     return;      function a() {} } b(); alert(a); 

Using the code above, the browser will alert "1".

I'm still unsure why it returns "1". Some of the things he says come to mind like: All the function declarations are hoisted to the top. You can scope a variable using function. Still doesn't click for me.

like image 743
dev.e.loper Avatar asked Sep 21 '11 21:09

dev.e.loper


People also ask

Can functions be hoisted in JavaScript?

Hoisting is a JavaScript technique which moves variables and function declarations to the top of their scope before code execution begins. Within a scope no matter where functions or variables are declared, they're moved to the top of their scope.

What is scoping function in JavaScript?

JavaScript has function scope: Each function creates a new scope. Variables defined inside a function are not accessible (visible) from outside the function. Variables declared with var , let and const are quite similar when declared inside a function.

Do function expressions get hoisted?

Function expressions in JavaScript are not hoisted. Therefore, you cannot use function expressions before defining them. This is all there is to be kept in mind for creating functions from a hoisting point of view.

Is VAR hoisted in JS?

The JavaScript engine hoists the variables declared using the let keyword, but it doesn't initialize them as the variables declared with the var keyword. The JavaScript engine doesn't hoist the function expressions and arrow functions.


1 Answers

Function hoisting means that functions are moved to the top of their scope. That is,

function b() {      a = 10;      return;      function a() {}  }  

will be rewritten by the interpeter to this

function b() {   function a() {}   a = 10;   return; } 

Weird, eh?

Also, in this instance,

function a() {} 

behaved the same as

var a = function () {}; 

So, in essence, this is what the code is doing:

var a = 1;                 //defines "a" in global scope function b() {      var a = function () {}; //defines "a" in local scope     a = 10;                 //overwrites local variable "a"    return;       }        b();        alert(a);                 //alerts global variable "a" 
like image 189
Peter Olson Avatar answered Sep 21 '22 13:09

Peter Olson