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
79.22K
hector
60.43K
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#