Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puzzled by this JavaScript code snippet

Tags:

javascript

For this snippet, I'm not surprised global variable 'a' evaluates to be 5.

http://jsfiddle.net/MeiJsVa23/gZSxY/ :

var a = 10;

function func(){
  a = 5;
}

func();   // expect global variable 'a' to be modified to 5;

alert(a); // and this prints out 5 as expected. No surprise here.
​

But how come for this code snippet, global variable 'a' evaluates to be 10 and not 5? It's as if the a = 5 never happened.

http://jsfiddle.net/MeiJsVa23/2WZ7w/ :

var a = 10;

function func(){
  a = 5;
  var a = 23;
}

func();   // expect global variable 'a' to be modified to 5;

alert(a); // but this prints out 10!! why?

like image 443
sivabudh Avatar asked Jul 09 '12 14:07

sivabudh


People also ask

What is code snippet in Javascript?

A code Snippet is a programming term that refers to a small portion of re-usable source code, machine code, or text. Snippets help programmers reduce the time it takes to type in repetitive information while coding. Code Snippets are a feature on most text editors, code editors, and IDEs.


1 Answers

This is due to variable hoisting: anything defined with the var keyword gets 'hoisted' to the top of the current scope, creating a local variable a. See: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting

like image 50
Graham Avatar answered Sep 26 '22 06:09

Graham