5 nifty JavaScript tricks that you may not know
Over the years, I have seen several JavaScript techniques that are particularly clever. Here's a short list of 5 such techniques that I have been using again and again. I hope it inspires you too to rethink how you write certain piece of code.
1. A compact string comparison
Let's say you want to check if a string value is present in a set of strings. You obviously go for a if
statement 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();
}
Written by Veera
Related protips
2 Responses
Would love to hear about the reader's tips and tricks! :)
over 1 year ago
·
Thanks, this is very helpful!!!
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Web
Authors
johnbender
77.79K
hector
56.26K
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#