DEV Community

Cover image for Destructuring Tweets - Episode 6 - Default Parameter Values
Kai
Kai

Posted on

Destructuring Tweets - Episode 6 - Default Parameter Values

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

Snippet of the Week

This week's snippet is from Agira Technologies:

let year = 2020;
const evolution = (defaultYear = 2000) => {
  year = defaultYear;
}
evolution(null);
console.log(year);
Enter fullscreen mode Exit fullscreen mode

At first, a variable year gets declared and initialized with the number 2020. Just to be manipulated in an arrow-function evolution in the very 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 with 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 that 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.

Snippet Summary

  • Trickery: When is a default parameter value applied
  • Key Learning: Null is indeed a value and therefore a valid argument
  • Further Reading:

Top comments (0)