5 nifty JavaScript tricks that you may not know

I like the first one the most from this post, so I am posting it here, but the others are cool too. 

1. A compact string comparision

Let’s say you want to check if a string value is present in a set of strings. You obviously go for a ifstatement as below.

if(fruit === 'apple' || fruit === 'banana' || fruit === 'chikoo'){
    doMagic();
}

Here’s a compact version of above code:

if({apple:1,banana:1,chikoo:1}[fruit]){
    doMagic();
}

This trick works well only if you have a small set of strings to compare.

http://veerasundar.com/blog/2014/09/five-nifty-javascript-tricks/

It's only fair to share...Tweet about this on TwitterShare on FacebookEmail this to someoneShare on Google+
This entry was posted in JavsScript. Bookmark the permalink.