Skip to content

Instantly share code, notes, and snippets.

View matix's full-sized avatar

Matias Figueroa matix

  • Eventbrite
  • San Francisco, CA
View GitHub Profile
@matix
matix / 01-js-scoping-problem.js
Last active June 1, 2022 21:46 — forked from anonymous/Array.forEach.js
Scoping and variable hoisting are two of the most challenging subjects to learn when picking up javascript, because it is fundamentally different from the other C-like languages' behavior. Javascript, unlike C and others, creates a new variables scope for each CLOSURE created, not for each BLOCK. This leads to some confusion in some cases. Here'…
var array = ["zero","first","second","third","fourth","fifth"];
var closures = [];
for(var i=0, l=array.length; i<l; i++){
closures.push(function(){return array[i]});
}
closures[3]();
// Expected "third", but actually returns 'undefined',
// because js did not create a separate scope for the "for" block