Created
October 11, 2012 20:47
-
-
Save alejandrolechuga/3875373 to your computer and use it in GitHub Desktop.
Tip of the : Undeclared Variables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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