Skip to content

Instantly share code, notes, and snippets.

@alejandrolechuga
Created October 11, 2012 20:47
Show Gist options
  • Save alejandrolechuga/3875373 to your computer and use it in GitHub Desktop.
Save alejandrolechuga/3875373 to your computer and use it in GitHub Desktop.
Tip of the : Undeclared Variables
//Tip of the day
//Variable declaration
//Every declaration out of any scope becomes
//part of the global object like
var i = 0;
var j = 0;
var bar = function () {};
// A common JavaScript bug is with the undecleared variables in any scope they become part of the global object as well
function kiss() {
// anti-pattern ↓
// How many kisses you want?
k = 2;
return k;
}
kiss(); // <----- Returns a defined number of kisses
// oh look is part of the global object !!
console.log(k);
console.log(this.k);
console.log(window.k); // window is reference to the global object in the browser environment.
function kissMe () {
// anti-pattern ↓
for (k = 0; k < 10000000; k++) {
kiss();
}
return "My job is done here";
}
kissMe(); // <----- Ask for kisses 10000000 times.
// Opps we're stuck with infinite kisses :( we are dead now next time declare your variables like this
function kiss() {
var k = 2; // How many kisses mom gave you ?
return k;
}
function kissMe () {
for (var k = 0; k < 10000000; k++) {
kiss();
}
return "My job is done here";
}
kissMe ();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment