In this article I will share with you some tips about JS that can improve your skills in JS !
Includes method to avoid multiples checking
You can easily replace this
if (value === 'a' || value === 'b' || value === 'c') { ... }
By
if (['a', 'b', 'c'].includes(value)) { ... }
More cleaner and you avoid to have too much condition in your if
Double !
operator to convert any variable into boolean
The !
(NOT) operator can be use two times !!
in order to convert any variable into boolean (like Boolean function), very convenient when you need to check some value before handle it.
const toto = null
!!toto // false
Boolean(toto) // false
if (!!toto) { } // toto is not null or undefined
Optional chaining
In javascript
you will need to often check if some property of your object exist before handle it. So many dev use this :
const toto = { a: { b: { c: 5 } } }
if (!!toto.a && !!toto.a.b && !!toto.a.b.c) { ... } // toto.a.b.c exist
You can use optional chaining
in order to avoid to use a multiple checker like above.
const toto = { a: { b: { c: 5 } } }
if (!!toto.a?.b?.c) { ... } // toto.a.b.c exist
// If the key doesn't exist, it will return undefined
const test = toto.a?.b?.c?.d // undefined
Avoid Else when you return value in your if
I have seen this multiple time :
if (...) { // the condition is not important in this example
return 'toto'
} else {
return 'tutu'
}
If your if return value you can just replace the code above by :
if (...) { // the condition is not important in this example
return 'toto'
}
return 'tutu'
If you need to use else if you can but you NEED to return a value for each else if!
Avoid ForEach, use more Filter, Map, Reduce, Every & Some function
My best advice from this article, as beginner we use a lot of the forEach function, but JS offers you a lot of alternative, and moreover theses function are FP (functional programming).
What are theses function ? I will explain you when use it !
Filter
As named, it allow us to filter some value in your array depending on your condition
const toto = [1, 2, 3, 4]
const evenValue = toto.filter(currentValue => {
return currentValue % 2 == 0 // remove all value that return false with this condition
}) // [2, 4]
Map
Use map when you need to transform all items in your item into another item, for exemple if you want to transform all of your number and multiply them by 2
const toto = [1, 2, 3, 4]
const valueMultiplied = toto.map(currentValue => {
return currentValue * 2 // remove all value that return false with this condition
}) // [2, 4, 6, 8]
Reduce
The most difficult to understand, unliked other function, reduce has another thing, the accumulator
, wtf is this and when use it ?
A good rules to know if you need to use reduce
:
Do you need to get a single value from your array ?
For exemple if I want to sum all number in your array into one value, you will need reduce
and the accumulator
is the sum ! And as any value, you need to initialise it !
const toto = [1, 2, 3, 4]
const sum = toto.reduce((accumulator, currentValue) => {
return accumulator += currentValue // you always need to return the accumulator
}, 0) // 10
Some & Every
One of my favorite, I don't use them everyday but I like it !
some
will check all of your item and when one of the item match your condition
, it will return true
, else it will return false
.
every
will check all of your item and when one of the item don't match your condition
, it will return false
, else it will return true
.
But when use it ?
For exemple if you need to be sure that all of your item match a condition !
const toto = [ 2, 4 ]
if (toto.every(val => val % 2 === 0)) { } // You are sure that your array contains only even value
const falsyToto = [ 2, 4, 5 ]
falsyToto.every(val => val % 2 === 0) // return false since array contain a odd value !
You can use some
in the contrary context, for exemple if you want to be sure that your array contain at least
one odd value
const toto = [ 2, 4, 5 ]
toto.some(val => val % 2 !== 0) // return true
I hope you like this reading!
🎁 You can get my new book Underrated skills in javascript, make the difference
for FREE if you follow me on Twitter and MP me 😁
Or get it HERE
☕️ You can SUPPORT MY WORKS 🙏
🏃♂️ You can follow me on 👇
🕊 Twitter : https://twitter.com/code__oz
👨💻 Github: https://github.com/Code-Oz
And you can mark 🔖 this article!
Top comments (23)
Very Nice
Some of the features are from ES6 and later
For some older browsers, use indexOf in place of includes:
While I encourage developing for clients that have no problems to adapt only mainstream browsers like chrome. firefox, you can persuade them to avoid using deprecated browser support for better code readability.
Yea, we should take advantage of the newer syntax and utilize tools like babel to transpile for older browsers.
Nice thank you Rohit!
Nice Article
Btw, you don't have to use the double not (
!!
) operator in a condition. It is enough to just writebecause an
if
statement checks thetruthy
ness (or thefalsy
ness) of the value.falsy
values are:false
0
(zero)""
(empty string)null
undefined
NaN
Everything else will be treated as
truthy
.The same rules apply to
Boolean(value)
and!!value
.This also works inside other boolean expressions so you can write for example:
->
If the body of the response istruthy
and the item field istruthy
: assignitem = response.body.item
. If either of them isfalsy
assignitem = 'default'
.Nice to know this! Thank you for sharing this it's very interesting Whaison
Amazing article on how to make your code look more professional. Thanks for sharing these great tips!
You suggested avoiding forEach, but provided no reason not to. Can you please explain why not? It accepts a function for its input parameter, just like all the other functional programming examples you provided. Is it, for example, slower than a loop? Is it more of a memory hog than map?
HI, I wouldn't avoid forEach in favor of map, each method basically does the same thing: given an array of elements, execute a callback function on each of the elements, the main difference for me is that while forEach mutates the original array, map instead returns a new array of the same size with the result of the callback on each element of the original array, which is something to consider if you might need the original data later on your code.
If you want to "do something" with the data (logging it, storing it), you may use forEach without problems, but if you want to modify the data (the famous "double the number" example we see everywhere, or parse the data from an array of objects in any way), map is your best friend, because it will return a new array with the result of your operations.
I'm not 100% sure, but I think map is faster than forEach, and another cool feature is method chaining; with map you can do something like
myArr.map().filter().reduce() // and so on
.Is just a matter of what are you trying to accomplish.
I hope this was helpful! Take care!
Thanks dude it the explication that my article miss about foreach!
You don't need need for each in order to change item in the current array.
It not respect fp (function al programming) if you use for each since you are currently mutating the array that are being iterated!
Moreover foreach function return nothing
I think he's trying to say that beginners use
forEach
in situations in which other methods such asmap
,reduce
, etc. are more appropriate.I don't really think you should avoid
forEach
completely. But it is a good idea to see if you can use any of the other of the FP methods first.It's a strange article for me.
TLDR; how to improve your JS skill? Use JS functionality! Okay...
IMO. You can take a higher level and, for example, explain why such code (@epresas ) is not very efficient in terms of performance.
myArr.map().filter().reduce() // and so on.
should it be below ?
hey thanks for your comment, yes it's working in case of you only need to return something! If you add more logic in the if or after you cannot use ternary (unlike you create function).
The other point is about else if! If you need to have else if is more complicated!
hey thanks for your comment, yes it's working in case of you only need to return something! If you add more logic in the if or after you cannot use ternary (unlike you create function).
The other point is about else if! If you need to have else if is more complicated!
thanks you so much
I think using a switch is better than Array.includes. Includes is very very slow. ~95% slower than using a normal if or switch statement.
Equally fast on Chrome 89: jsben.ch/O1q01
Modern browsers are clever.
Thank you so much!