Tips and Tricks
1) Getting an array from behind to front
Given the array:
1 | const animals = ['Otter', 'Badger', 'Alpaca', 'Sloth']; |
We can get each item in the array from behind to front by doing this:
1 | animals.slice(-1); // ['Otter'] |
2) Short-circuit
Instead of doing:
1 | if (condition) { |
You can just simply:
1 | condition && callMe(); |
3) One liner if
else
statement
The long way:
1 | const age = 10; |
The one liner way:
1 | console.log(age >= legalAge ? 'Drink beer!' : 'Drink milk or something else!'); |
4) typeof
in validation
typeof
can be useful in validation data validation. Let’s say you have a simple addition function that takes 2 arguments as addends then returns the sum. You want to make use that the arguments being passed are really numbers and not objects or string. You can do that by using typeof
.
1 | const add = (x, y) => { |
By this solution, you can make sure that the addends are number.
5) Assigning alternative value to a falsy variables
Say you a variable color
which is undefined. You can add an alternative value to it by using the ||
operator.
1 | const color = undefined; |
Who wants a green alpaca?
Special thanks to contributor : Jofferson Ramirez Tiquez