public
Created

Tip of the : Undeclared Variables

  • Download Gist
tip1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
//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 ();

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.