DEV Community

Cover image for Improve your JS skills with those tips #1
Code Oz
Code Oz

Posted on • Updated on

 

Improve your JS skills with those tips #1

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') { ... }
Enter fullscreen mode Exit fullscreen mode

By

if (['a', 'b', 'c'].includes(value)) { ... }
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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'
}
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 !
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

🎁 MY NEWSLETTER

β˜•οΈ 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 (24)

Collapse
 
heyrohit profile image
Rohit Gupta

Very Nice

Some of the features are from ES6 and later
For some older browsers, use indexOf in place of includes:

if (['a', 'b', 'c'].indexOf(value) > -1) { ... }
Enter fullscreen mode Exit fullscreen mode

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.

Collapse
 
kenovienadu profile image
Ovienadu Ken

Yea, we should take advantage of the newer syntax and utilize tools like babel to transpile for older browsers.

Collapse
 
codeoz profile image
Code Oz

Nice thank you Rohit!

Collapse
 
whaison profile image
Whaison • Edited

Nice Article

Btw, you don't have to use the double not (!!) operator in a condition. It is enough to just write

if (value) { 
  ...
}
Enter fullscreen mode Exit fullscreen mode

because an if statement checks the truthyness (or the falsyness) 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:

let item = response.body && response.body.item || 'default'
Enter fullscreen mode Exit fullscreen mode

-> If the body of the response is truthy and the item field is truthy: assign item = response.body.item. If either of them is falsy assign item = 'default'.

NOTE: in JavaScript the && and || operators work differently than in other languages

left && right === left  // if left is falsy
left && right === right // if left is truthy

left || right === right // if left is falsy
left || right === left  // if left is truthy
Enter fullscreen mode Exit fullscreen mode
Collapse
 
codeoz profile image
Code Oz

Nice to know this! Thank you for sharing this it's very interesting Whaison

Collapse
 
yuridevat profile image
Julia πŸ‘©πŸ»β€πŸ’»

Amazing article on how to make your code look more professional. Thanks for sharing these great tips!

Collapse
 
jlitowitz profile image
Jason Litowitz

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?

Collapse
 
epresas profile image
epresas • Edited

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!

Collapse
 
codeoz profile image
Code Oz

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

Collapse
 
nicozerpa profile image
Nico Zerpa (he/him)

I think he's trying to say that beginners use forEach in situations in which other methods such as map, 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.

Collapse
 
lukeshiru profile image
Luke Shiru

lol I saw your second part first, but here's a comment for the first part as well:

About your "Avoid Else when you return value in your if", if you'll gonna do that, then you can just use a ternary instead:

return (...) ? "toto" : "tutu";
Enter fullscreen mode Exit fullscreen mode

I generally don't write if and use ternaries because they "force me" to have all the branches covered (kinda like every if has a mandatory else), so I don't see much value in skipping the else.

Cheers!

Collapse
 
codeoz profile image
Code Oz

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!

Collapse
 
xr0master profile image
Sergey Khomushin

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.

Collapse
 
manoharreddyporeddy profile image
Manohar Reddy Poreddy
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'
Enter fullscreen mode Exit fullscreen mode

should it be below ?

return (...) ? 'toto': 'tutu' ;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
codeoz profile image
Code Oz

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!

Collapse
 
thanhtanpm2000 profile image
ThanhTanPM2000

thanks you so much

Collapse
 
asimarra profile image
Angelica Maria

Thank you so much!

Collapse
 
danielatwood profile image
Daniel Atwood

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.

Collapse
 
ambyjkl profile image
Ambareesh "Amby" Balaji

Equally fast on Chrome 89: jsben.ch/O1q01
Modern browsers are clever.

Collapse
 
kennyrafael profile image
kennyrafael

Hi, awesome content! I have also a post about these and other tips. Here at dev.to

Collapse
 
bhagirath1312 profile image
Bhagirath Bhatti

Nice thank you for improve JS πŸ™‚

Collapse
 
amandaolsen profile image
amandaolsen

Why use the Double !! when you could use the Boolean function?

Collapse
 
qq449245884 profile image
qq449245884

Dear CodeOz,may I translate your all dev articles into Chinese?I would like to share it with more developers in China. I will give the original author and original source.

Collapse
 
r2h_4869 profile image
R2h1

关注 δΊ† Twitter ζ€ŽδΉˆθŽ·ε–Underrated skills in javascript, make the difference

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.