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.
Here’s a compact version of above code:
This trick works well only if you have a small set of strings to compare.
!!val. Very useful if you want to check if a value is a present or not.
!! might confuse people with
! operator which has a different meaning. So make a good judgement before you use
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
Here’s an alternative, short approach:
4. Chaining of function calls
You have three functions
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
But let’s rewrite with this one:
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:
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.