Writing Clean Code in JS
1 min readAug 18, 2020
- Keep functions small.(Preferably < 30, but never more than 50).
- Concise use of if/else. Keep the if/else depth to max of 2 levels.
- Concise use of try/catch. try/catch should be first statement in function.
- Use forEach/map/reduce/flatMap(chain)/transduce etc. while looping arrays. Avoid for loops until necessary.
- 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 - Practice KISS(Keep it simple stupid), DRY(Don’t repeat yourself) and YAGNI(You aint gonna need it).
- Keep Patience. It took time to learn things. https://www.norvig.com/21-days.html
- Read Pragmatic Programmer and Clean Code.