Writing Clean Code in JS

Sandeep Sharma
1 min readAug 18, 2020
  1. Keep functions small.(Preferably < 30, but never more than 50).
  2. Concise use of if/else. Keep the if/else depth to max of 2 levels.
  3. Concise use of try/catch. try/catch should be first statement in function.
  4. Use forEach/map/reduce/flatMap(chain)/transduce etc. while looping arrays. Avoid for loops until necessary.
  5. Avoid unnecessary promise wrapping. Understand Promise “then”, it acts like ‘map’ on scalar values and ‘flatMap’ on wrapped promises. e.g Promise.resolve(1)
    .then(a => a * 2) // a = 1 here, acts like map
    .then(a => Promise.resolve(a * 2)) // a = 2, acts like flatMap.
    .then(a => console.log(a)) // a = 4
  6. Practice KISS(Keep it simple stupid), DRY(Don’t repeat yourself) and YAGNI(You aint gonna need it).
  7. Keep Patience. It took time to learn things. https://www.norvig.com/21-days.html
  8. Read Pragmatic Programmer and Clean Code.

--

--