re: Practical Ways to Write Better JavaScript VIEW POST

FULL DISCUSSION
 

Solid tools and advice. Out of curiosity what is your opposition/alternative to using null? Sometimes it is a bit unavoidable depending on the backend/backend team you are working with and can also help to show intent that something is purposefully w/out a value.

 

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
 

This is a very very good reply.

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

Is especially accurate. It's not that I think null can't be used well, I just don't understand why it fits in a incredibly high-level language like JS. Great comment.

code of conduct - report abuse