null, undefined, and default values

Ran Wahle
Israeli Tech Radar
Published in
1 min readJul 3, 2019

Take a look at the following code

As you may tell, this function, supposedly makes sure, that you get an array. However, this can only work, if you don’t send any parameter to the function, or send undefined, which is the same.

What about null?

Well, null is a value, and in that case, the default value won’t take effect, and the runtime will produce an error of “ TypeError: Cannot read property ‘map’ of null”

So, what can you do?

You may simply validate, fortunately, the not(!) operator returns false for both null and undefined, alternatively you may use the Array.isArray method, if you want to make sure you will have a map operator.

Wrapping up:

Although default parameters is a great ES feature, we must not rely on it and still validate our data. It works perfectly for undefined but null is a value, and therefore you cannot expect default value to take effect.

--

--