Welcome to my blog where I write mostly about technical things!

Destructuring Tweets – Episode 6 – Default Parameter Values

Welcome to the series about destructuring those over-shared JavaScript quizzes on Social Media. Have fun digging into default values!

The Snippet

let year = 2020;
const evolution = (defaultYear = 2000) => {
  year = defaultYear;

At first, a variable year gets declared and initialized with the number 2020. Just to be manipulated in an arrow-function evolution in the next line. It accepts a parameter with a default value of 2000. This parameter's value gets assigned to the variable year.
Now comes the exciting part. The function gets called null as the argument, followed by logging the manipulated variable to the console.

The Output

You have a relatively high chance of 50 % to guess the output right here. As it's either 2000 or null, right? The initial value of 2020 gets surely overwritten.
However, null wins. And there is a good reason for that.

The Analysis

The reason is that null is indeed a value. It means the intentional absence of any other matter. It stands for “nothing” or “void”.
That's different with undefined. Undefined is a primitive type (and a value), meaning a variable does not have a value assigned.
So, if we leave out an argument in a function call, we do not pass “no value” but rather undefined. And that logic is also applied when it comes to default parameters. Only if “no value”, so undefined, is passed, it gets overwritten by the defined default value.

Further Reading

Default Parameters