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.
And, please note that some people may think clever coding impacts readability and they might be right. So, grasp the concept and apply it in your code wherever you think it helps.
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 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(); }
This trick works well only if you have a small set of strings to compare.
2. !!
Here’s a shortest way to convert any JavaScript value to its truthy / falsy representation – just use !!val
. Very useful if you want to check if a value is a present or not.
For example,
if(!!document.addEventListener){ doMagic(); }
But !!
might confuse people with !
operator which has a different meaning. So make a good judgement before you use !!
everywhere.
3. Conditional function call
If a value is true, you want to call a function foo() otherwise you want to call bar(). You go for if
, right?
if(param){ foo(); }else{ bar(); }
Here’s an alternative, short approach:
param ? foo() : bar();
yay!
4. Chaining of function calls
You have three functions one()
, two()
and three()
. You want to call these functions one after other, but only when a previous function returns a truthy value. For example, if all three functions returns a truthy value, then all will be called. But if the function two()
returns false/null then function three()
won’t be called.
So, you go for if
, obviously.
if(one()){ if(two()){ three(); } }
But let’s rewrite with this one:
one() && two() && three();
5. IIFE
IIFE is short for Immediately Invoked Function Expression. It means, you define a function and then you call it immediately. IIFE helped me in some usecases where I don’t want to create a new function but I needed the logic to be inside a function block.
For example, lets say you are initializing variables and for one variable, the initial value needs to be calculated using some complex logic. If you don’t want to separate this calculation logic to a seperate function, but you still want to wrap it in it’s own block, you can IIFE. Like below:
function doMagic(){ var foo = 1, bar = 2, zoo = (function(){ // some complex stuff // some more complex stuff return stuff; }()), baz = 3; }
So, what do you think about these tricks? Do you think these are usefull or affect the code readability? Feel free to comment your thoughts.
Reference: | 5 nifty JavaScript tricks that you may not know from our WCG partner Veera Sundar at the Veera Sundar blog. |
Even more JavaScript and AngularJS tricks at my blog post http://bahmutov.calepin.co/angularjs-and-javascript-nuggets.html
The example for !!
if(!!document.addEventListener){
doMagic();
}
isn’t very good. It does the same thing as
if(document.addEventListener){
doMagic();
}
!! is for type casting to a boolean, which matters if you’re trying to assign the reulting cast value to a variable.
Although the tips are all quite clever, I would be careful with #3 and #4. Especially #4 and similar tricks to it, such as conditional function calls using the or operator ||, can lead to code that’s hard to follow.
It would be better formatted as if(one() && two()) { three(); } which achieves the same result without looking so out of place.
#4 relies on a side-effect, which is never a good idea. Compiler optimization may cause code to be executed in an order not intended.
Third one is wrong: (param ? foo : bar)(); is better.
I’ve not seen #1 before. The method that I use for checking membership of a list is
[ ‘apple’, ‘banana’, ‘chikoo’ ].indexOf(fruit) >= 0
New Trick to convert a arguments object to an Array
arguments.constructor = Array;
This is much simpler to write and to understand than the commonly seen
Array.prototype.slice(arguments, 0);
I think there are great some of them make JS look more like PHP like- param ? foo() : bar();
Yeah, I don’t know this trick before ;)
I really love the first example. Could you explain more about this example? (#1)
Thank you very much:)
@Giảm Mỡ Bụng Tại Nhà Trick #1 works as follows: {…} is an object – we’ll discuss what is in it in a few seconds {…}[name] extracts the object property value associated with the named object property in exactly the same way as using an index to get an element from an array. In fact, an array (in JavaScript) is an object with properties named 0, 1, 2, etc and whose property values are the elements in the array; and you can add named properties to the array as well as to any other object. For this trick, the object… Read more »
Typo in my reply
“So, doing {…}[name] finds the value 1 for the property with the given name and returns ‘undefined’ if the named property is in the object. ”
Should read
“So, doing {…}[name] finds the value 1 for the property with the given name and returns ‘undefined’ if the named property is NOT in the object. ”
Sorry!
Good and very useful article for developing and managing web application in a technical ways. This information can help the developers to modify any tricks without any hesitation.
Also for building a short type of plugin this can also help to rebuild the construction of a page.
Thanks a lot.
—
Regards,
Sourav Basak [Blogger, Entrepreneur, Thinker]
http://www.namasteui.com
Syntax error in #5.
zoo = (function(){
return stuff;
}()),
Should be:
zoo = (function(){
return stuff;
})(),
The first set of parens enclose the anonymous function definition, the second trailing set of parens invoke the function. BTW: you can also pass values to the anonymous function in the trailing parens, which are not required in this example because the anonymous function doesn’t take any.