Really Bad Code
by Elijah Manor
JavaScript
if ( someString != null && someString.length > 0 ) {
//Do something here...
}
if ( someString == null ) {
someString = "default Value";
}
someString = someString ? someString : "default value";
console.log( 0 == '0' ); //true
//Bad way to declare objects and arrays
var person = new Object(),
keys = new Array();
var myArray = [], name;
myArray[5] = "test";
console.log( myArray.length ); //6
for ( name in myArray ) {
console.log( name, myArray[name] );
//Outputs...
// 5, test
}
//broken
var unorderedList = $( "ul" ), i;
for (i = 0; i < 10; i++) {
$("<li />", {
id: i,
text: "Link " + i,
click: function() {
console.log("You've clicked " + i);
}
}).appendTo( unorderedList );
}
var iAmGlobal = "Keep these to a minimum";
iAmGlobalToo = "Bad";
function oldSchoolWay() {
iAmGlobalNooo = "Really Bad"; //Put in global scope when executed
console.log( "Bad oldSchoolWay Function" );
}
//Bad way to prevent namespace clashing
function namespace_oldSchoolWay() {
console.log( "Worse oldSchoolWay Function" );
}
//Functions
window.oldSchoolWay();
window.namespace_oldSchoolWay();
//Global variables are available off window object
console.log( window.iAmGlobal );
console.log( window.iAmGlobalToo );
console.log( window.iAmGlobalNooo );
//Where You Can Get Into Trouble
console.log( someVariable ); //undefined
var someVariable = 42; //Global variable
console.log( someVariable ); // 42
function doSomething() {
console.log( someVariable ); // undefined
//Why is someVariable undefined?
//Developer expected to see 42 from global variable
someVariable = 1
console.log( someVariable ); // 1
console.log( window.someVariable ); // 42
//Why is window.someVariable 42?
//Developer thought he just set global variable to 1
if ( false ) {
var someVariable = 0;
}
}
doSomething();
console.log( someVariable ); // 42
//Why is...