logo

NJP

Default Parameters - Let's Learn ECMAScript 2021 with Earl Duque

Import · Jan 25, 2024 · video

All right in this one. It's another nice quality of life upgrade. It's called default parameters. So if you take a look at the script that
I have on the screen, I have a function. It's called createIncident. I'm expecting two parameters,
a description and a priority. and when I call that function,
simply return whatever I said back in a log statement. So I'm going to create an incident
with both parameters provided. So this first one, it's a service outage. and the priority is high. And then on the second time
I call this function, I'm only going to provide
the first parameter. Let's say I just forgot
to provide the second parameter or there was no second parameter
for me to be provided. So if I press run script just as I expected,
the first one works as intended. Here's that description
and here's that priority high. And then on the second one, it's
what I expected. The description
and the priority was undefined. I never provided the parameter. For default parameters
introduced in newer ECMAScript We can simply say priority equals low. So providing this syntax here
means if we're missing a parameter, it will simply default
to whatever I put in there. So if I run the script again, there
you go. It automatically forced it to low because
I didn't provide that second parameter. So default parameters is all about
using them effectively, right? So here's a fine use case for it. So say we have a log message function where we have the message
and we have the timestamp, but if the timestamps not provided, I'm
going to go ahead and force it to pull up a timestamp. So from this example,
it's kind of like the reverse. Usually we don't provide that
second parameter because the timestamp we want it to default to whatever
the current date time is. So you can see in this usage
of that function, our normal behavior is just providing a message and the timestamp
is automatically generated by default. But what if we needed
to override that timestamp? Now we can simply provide
that as a parameter. and there you go. That string that I provided overrides the default
that was provided from the beginning.

View original source

https://www.youtube.com/watch?v=1qx93zFmTHg