re: Practical Ways to Write Better JavaScript VIEW POST

re: Solid tools and advice. Out of curiosity what is your opposition/alternative to using null? Sometimes it is a bit unavoidable depending on the back...

I'm curious as to when you would want to explicitly pass/accept an argument that has no value within JS... Most programmatic behavior happens within arrays (hence the large drive for people to now grasp map, filter, and reduce) and on objects/hashes/maps/whatev your language calls them. In the case of the array, a null or undefined is most likely something you're only going to care about skipping over so your program doesn't crash. And in the case of the object, why look to operate on a parameter that you don't expect to be set?

Especially when it comes to forEach, map, and reduce, the better option than null is usually a default, blankish value, like 0 for addition/subtraction, 1 for multiplication/division, "" when you expect to be working with strings, [] for when you expect to be processing a list, and {} when you're expecting an object. As an added bonus, while they aren't technically able to prevent type bugs, using defaults in function signatures can hint to other developers what the types of their arguments should be.

function convolutedExample(numbers = []) { 
  // maybe something using an object would've been less convoluted...
  return numbers.reduce(((product, factor = 1) => product * factor), 1)

convolutedExample([1, 3, undefined, 4]); // returns 12
convolutedExample();                     // doesn't crash
code of conduct - report abuse