Javascript best practices – Part 1/6

Category : web

Date : February 5, 2015

Below are some of the best practices which can be really useful when working on a large scale javascript application.

In Part I of this best practices tutorial we will be seeing using switch fall-through methods , better conditioning and some examples of good and bad practices we use in our day-to-day routine. For testing you can set up a simple html file or you can use the browser console.

  1. USING SWITCH & FALL-THROUGH

We will start with most commonly followed logic block. if-else

// Let make a constructor for hotels function Hotel (name,type) { this.name = name; this.type = type; if (type == 1) { this.category = ‘Trending’; case 2: this.category = ‘Brilliant’; } else if (type == 3) { this.category = ‘PocketFriendly’; } else if (type == 4) { this.category = ‘LateNights’; } else if (type == 5) { this.category = ‘StreetFood’; } } // We will make a hotel variable and we assigned it a Hotel from the constructor var hotel = new Hotel(‘Rotiwala’,3); console.log(hotel.category); // Output: Pocket Friendly

Even-though this runs fine and is the most straight forward method but a better way would to handle multiple case using switch case.

// Correct way to handle such situation would be to use switch function Hotel (name,type) { this.name = name; this.type = type; switch (type) { case 1: this.category = ‘Trending’; break; case 2: this.category = ‘Brilliant’; break; case 3: this.category = ‘PocketFriendly’; break; case 4: this.category = ‘LateNights’; break; case 5: this.category = ‘StreetFood’; break; // Passing Default values for handling exceptions default: console.log(name+"\t Wrong type passed");

}

} var hotel = new Hotel(‘Rotiwala’,3); console.log(hotel.category); // Output: Pocket Friendly

Another usage of switch method with string labels and fall-through. Fall-through is the method of passing properties to a set of cases stacked before a break;

// Using Fall-Through in javascript switch function Hotel (name,type) { this.name = name; this.type = type; switch (type) { case 1: this.category = ‘Trending’; break; case 6: this.category = ‘Brilliant’; break; case 7: this.category = ‘PocketFriendly’; break; case 3: case 4: this.category = ‘LateNights’; break; case 2: case 5: case 12: this.category = ‘StreetFood’; break; // Add strings as label case ‘new’: this.category = ‘Not Categorized Yet’; break; default: console.log(name+"\t Wrong type passed"); } } var hotel = new Hotel(‘Rotiwala’,‘new’); console.log(hotel.category);

Let us take a actual scenario where we can use javascript switch and fall-through.

{% highlight javascript linenos %} /* Usage of fall-through can be maximum utilised when there is precedence based properties are involved */ function HotelCadre (hotel, tags) { this.name = hotel; switch(tags){ case “ac”: this.ac = true; case “dinein”: this.dinein = true; case “non”: this.nonVegServing = 5; case “veg”: this.vegServing = 5; } } // Example: 1 var HotelsFacility = new HotelCadre(“Barbeque Nation”,“veg”); console.log(HotelsFacility); // Only takes name and vegServing Property in it. // HotelCadre {name: “Barbeque Nation”, vegServing: 5} // Example: 2 var HotelsFacility = new HotelCadre(“Barbeque Nation”,“ac”); console.log(HotelsFacility); // Only takes name and vegServing Property in it. // HotelCadre

  1. Conditional (Ternary) Operator

Normal conditioning method, Same old if-else block for every condition there exists can sometimes be a overkill.

var isAdult = false; var ticket; if(isAdult){ ticket = ‘Rs100’; }else{ ticket = ‘Rs20’;

console.log(‘Current ticket Rate’+ticket);

// Our Method someCondition ? ifTrue : ifFalse;

// Solving our ticket conditioning var isAdult = false; var ticket = isAdult ? ‘Rs100’ : ‘Rs20’; console.log(‘Current ticket Rate’+ticket);

//Even Better Solution to ticket conditioning var isAdult = false; console.log(‘Current ticket Rate’+ (isAdult ? ‘Rs100’ : ‘Rs20’));

// Compound Conditioning var isSenior = true; console.log(‘Current ticket Rate’+ (isAdult && isSenior ? ‘Rs100’ : ‘Rs20’));

// Function on Conditioning var isAdult = false; isSenior = true; !isAdult && isSenior ? (function() { console.log(‘isAdult and isSenior’); })() : (function() { console.log(‘ticket concession applicable’); })();

// Multiple Actions in Conditioning var ticket; var seat; var isAdult = false; isSenior = true; !isAdult && isSenior ? (ticket = ‘Rs20’,seat = ‘Front’) : (ticket = ‘Rs100’,seat = ‘Back’); console.log('ticket: ‘+ticket+’\nSeat: '+seat);

// Nested Conditioning var ticket; var seat; var isAdult = false; isSenior = false;isFemale = true; !isAdult && isSenior ? (ticket = ‘Rs20’,seat = ‘Front’) : isFemale ? (ticket = ‘Rs100’,seat = ‘Left’) : (ticket = ‘Rs100’,seat = ‘back’); console.log('ticket: ‘+ticket+’\nSeat: '+seat);

  1. LOGICAL OR (||) & AND (&&)

{% highlight javascript linenos %} // Logical Assignment [OR] // Creating an Object var hotels = { addHotel : function (hotel) { this.hotel = this.hotel || [ ]; this.hotel.push(hotel); } }; // Adding Hotels hotels.addHotel(“Anjappar”); hotels.addHotel(“Zaitoon”); hotels.addHotel(“Buhari”); hotels.addHotel(“Anjappar”); console.log(hotels.hotel); //[“Anjappar”, “Zaitoon”, “Buhari”, “Anjappar”]

// NOTE: List of all false values : 0, undefined, “”, NULL, NaN

// Logical Assignment [AND] /* indexOf method is an method of an array prototype which will examine an entire array and return the very first found index of any element. If element is not fount -1 is returned */ var isFoodie = true; // Creating an Object hotels.retreiveHotel = function (request) { return (this.hotel.indexOf(request) >=0) ? this.hotel.splice(this.hotel.indexOf(request),1)[0] : console.log(“No \t” + request + " Found"); } var hotel = isFoodie && hotels.retreiveHotel(“Zaitoon”); // Second true condition is taken inside hotel and Zaitoon will be printed console.log(hotel);

// More than two logical operator var isFoodie = true; var isHotelOpen = true; hotels.retreiveHotel = function (request) { return (this.hotel.indexOf(request) >=0) ? this.hotel.splice(this.hotel.indexOf(request),1)[0] : console.log(“No \t” + request + " Found"); } var hotel = isHotelOpen && isFoodie && hotels.retreiveHotel(“Zaitoon”); // Second true condition is taken inside hotel and Zaitoon will be printed console.log(hotel);

Will link the remaining post in this series here soon. If you have any questions, comments or suggestions, feel free to join the discussion below!