Tip: Watch out for null in default params
By Juan Manuel Allo Ron on Jun 4, 2020

Defaults in function parameters is a feature that simplified my code a lot. But there is one caveat that we need to be aware of! Let’s start with an example:
function say(message = 'Hello World') {
console.log(message)
}
Now, what’s the output of the following statements:
say('hi')
say()
say(undefined)
say(null)
Most of them will work as you would expect…but there is always a trick in JS… when calling say(null)
as null
is a value, the default won’t be triggered causing null
to be logged. In this example is easy to see it quickly, but this gets trickier in real world applications.
How do we avoid this?
I try not to use null
at all and that tends to reduce this problem. Are you using any other solution? I would love to hear about it.
Enjoy!!!
Catch up with me on X (twitter):@juan_allo
Share
---
Similar Articles

Lazy loading images with Intersection Observer
May 26, 2020
Images play a huge role in loading performance. Websites loading tons of images upfront can be paying a high price in terms of user experience…

Weekly Digest #1
Mar 22, 2020
Best practices on JavaScript modularity: when to use named exports, how to group code and what to avoid. Check JavaScript Module Best Practices.

Partial Application made easy with ES6
Nov 12, 2018
In this post I will present a quick example on how ES6 can improve readability and help build code that is easier to maintain. Also, I will be exploring partial application, a nice technique to keep in your developer toolbox.

Weekly Digest #7: On Javascript books
May 3, 2020
Whether you are learning JS from scratch or have been working with it for a while now, I believe you will find great value on the following list of books.