Default Parameters | JavaScript 🔥 | Lecture 119
Summary
TLDRThe video delves into the concept of default parameters in JavaScript functions, introduced in ES6. It starts by demonstrating the traditional ES5 approach, using logical OR operators and falsy values to set default parameter values. The instructor then introduces the more concise and intuitive ES6 syntax, where default values can be assigned directly in the parameter list. The video also explores the ability to use expressions and other parameter values to calculate dynamic defaults. Additionally, it covers the technique of passing `undefined` to skip a parameter and retain its default value. Throughout the tutorial, the instructor incorporates practical examples and explanations, making it an engaging educational resource on this JavaScript feature.
Takeaways
- 🔑 Default parameters in JavaScript functions allow you to set a default value for a parameter in case it is not provided when calling the function.
- 😃 Default parameters in ES6 can be set by assigning a value to the parameter in the function declaration, e.g., `function(param = 'default')` .
- 🔢 Default parameter values can be any expression, including calculations based on other parameters defined before it.
- ⚠️ You cannot skip arguments when calling a function; if you want to use a default value for a parameter, you must pass `undefined` as the argument for that parameter.
- 🏆 Default parameters make code more concise and readable compared to the old ES5 way of using logical OR operators to handle default values.
- 📝 The provided script uses an airline booking example to demonstrate the use of default parameters.
- 🌐 The script assumes strict mode is enabled, and it uses enhanced object literal syntax and array methods like `push()`.
- 🔁 The script suggests reloading the page in the browser to see the updated output after making changes.
- 🚀 ES6 introduced improvements to JavaScript, including default parameters, which make code more expressive and easier to write and maintain.
- 🧑💻 Understanding default parameters is essential for writing more robust and maintainable JavaScript functions.
Q & A
What is the purpose of this section in the video?
-The purpose of this section is to explain default parameters in JavaScript functions, which allow you to set default values for function parameters when they are not explicitly provided.
How were default parameters implemented before ES6?
-Before ES6, default parameters were implemented using logical operators like the OR operator (||) to check if a parameter was falsy (e.g., undefined) and then assign a default value if it was.
What is the ES6 syntax for setting default parameters?
-In ES6, you can set default parameters by assigning a value to the parameter in the function declaration, like so: `function(param = defaultValue) {...}`.
Can default parameters be dynamic expressions?
-Yes, default parameters can be dynamic expressions. You can use any valid JavaScript expression as the default value, including calculations based on other parameters.
Is it possible to skip a parameter and use the default value?
-Yes, you can skip a parameter and use its default value by passing `undefined` as the argument for that parameter when calling the function.
What is the advantage of using default parameters?
-Default parameters make it easier to handle optional function arguments, reducing the need for additional checks and assignments within the function body. They also improve code readability and maintainability.
Can default parameters reference parameters that are defined after them?
-No, default parameters can only reference parameters that are defined before them in the parameter list. This is because JavaScript evaluates parameters in order.
What is the purpose of the `createBooking` function in the example?
-The `createBooking` function is used to create an object representing a booking for an airline, with properties like flight number, number of passengers, and price. It demonstrates the use of default parameters.
How are the bookings stored in the example?
-The bookings are stored in an array called `bookings`. Each time the `createBooking` function is called, the resulting booking object is pushed into the `bookings` array.
What is the purpose of using `strict mode` in the example?
-The example uses `strict mode` in JavaScript, which enforces stricter parsing and error handling, and eliminates some silent errors that can occur in non-strict mode. It helps in writing more robust and secure code.
Outlines
🔢 Introducing Default Parameters in Functions
This paragraph introduces the concept of default parameters in JavaScript functions. It explains how default values can be assigned to function parameters, allowing the function to be called without explicitly providing those arguments. The paragraph walks through creating a basic booking function for an airline application and demonstrates how to set default values for the number of passengers and price. It showcases both the pre-ES6 approach using logical OR and the newer ES6 syntax with parameter assignments. The paragraph also highlights the ability to use expressions as default values, including referencing other parameters defined earlier.
🧭 Advanced Default Parameter Handling
This paragraph continues exploring advanced techniques for handling default parameters in JavaScript functions. It discusses the ability to override default values by passing explicit arguments during function calls. The paragraph then explains how to skip a default parameter value by passing 'undefined' as the argument, effectively leaving the parameter at its default value. It also mentions the importance of argument order when calling functions with default parameters. Overall, this section provides a comprehensive understanding of working with default parameters, including their behavior, usage scenarios, and potential pitfalls.
Mindmap
Keywords
💡Default Parameters
💡Short Circuiting
💡Enhanced Object Literals
💡Strict Mode
💡Array Methods
💡Expressions in Default Parameters
💡Parameter Order
💡Skipping Arguments
💡ES6 (ECMAScript 2015)
💡Function Parameters
Highlights
Sometimes it's useful to have functions where some parameters are set by default. This way, we do not have to pass them in manually in case we don't want to change the default.
We're going to continue with the airline theme that we started by the end of the last section.
We need to pass in the flight number, the number of passengers, and the price into the booking function.
Based on what we learned in the last section about short circuiting, how would we implement default parameters?
The old way of setting default parameters is to reassign the parameter like this: numPassengers = numPassengers || 1;
In ES6, we can set default values by writing this equals one, which looks a lot nicer and is more intuitive to read.
Default values can contain any expression, e.g., price = numPassengers * 199 * 1.2;
Default values can use the values of other parameters that were set before it.
We cannot skip arguments when calling a function, but we can set a parameter to undefined to skip it and use the default value.
Setting a parameter to undefined is the same as not setting it, so it will take the default value.
Default parameters are a nice addition to the language in ES6 and are straightforward to understand.
Transcripts
Let's start this section about functions
with one of the easiest parts, which is default parameters.
And a new section means new starter files.
So as always, get yours from the Gitup repository and then
open them up in your VS Code.
So as always, we already start with strict mode here
but now let's talk about default parameters.
So sometimes it's useful to have functions where some
parameters are set by default. This way
we do not have to pass them in manually in case we don't
want to change the default.
Now in this section,
we're gonna to continue with the airline theme that we
started by the end of the last section.
And so let's now create a very basic booking function and
we're gonna to do that,
starting with the knowledge that we already had previously.
So without the default
parameters first,
so just a normal function and into this function,
we need to pass in the flight number,
the number of passengers
and the
price.
And then let's simply use this data to create an object and
push that into some bookings array.
So booking,
and now here we can use the enhanced object literal syntax
that we learned about in the previous section.
So we cannot create an object with a flight num property
without having to do this, remember?
So we simply defined a variable here and that will then
create a property with this name and also the value that's
in the variable.
And then let's just log it to a console.
And then let's just create an array out here which will
contain these bookings.
So we start empty here then we simply push them each
time there is a booking.
So basically for the airline to keep
the bookings in some kind of
system.
And this is all very fictional.
It's just to show you the default parameters in this case.
And speaking of that,
based on what we learned in the last section about
short circuiting, how would we implement default parameters?
Well,
let's start by calling this function without specifying some
parameters and see what we get then.
So create booking.
And now with just the flight number, let's say LH 123,
and now we need a new terminal as always.
So again, I hit tap here
to auto complete the operation.
And indeed here is our browser with our page already
running.
Now here's some kind of problem.
Oh, and that's because we called this booking here,
the same as the array.
And so here it is then trying to push this object into
itself basically.
So we need to create bookings here, giving it a new name.
And so indeed now we get here the result of this object,
and now it works.
And here we see the result of this booking object.
And so what we wanted to see here was that the numPassengers
and the price are set to undefined because we didn't specify
them.
And so now we can use short circuiting to our advantage
because we know that these are falsy values.
Okay.
And what I'm doing here is basically the old way of setting
default parameters,
just to remember how it would work before ES6.
So let's say I wanted to set the number of passengers to one
by default.
So basically we would reassign this parameter like this.
So numPassengers is numPassengers or one,
which is the default value.
And this works because of the reasons that we learned in the
last section, which is that whenever this is a falsy value,
which undefined is,
then the result of the
OR operator here will be this second operant.
So this value here in this case one,
and now we can do the same thing with the prize.
Let's say 199 is the default price.
And so if we reload this now,
then indeed we get our default values here.
Okay. So coming from this part of the code, however,
this is a lot of ugly boilerplate coat. And again,
this is the ES5 way of doing it.
So I will take this out.
Let me actually, write
ES5 here because now in ES6 there is a better way.
So all we have to do is to write this equals one.
And so now this here will be the default value
and the same for the price.
Let's say to 199.
And now if we reload, then we get the same result here.
And this here of course, looks a lot nicer and is
a lot more intuitive to read.
Now, of course we can override these defaults.
Otherwise this wouldn't make much sense.
So let's try
H 123, and now for
two passengers, and let's say 800.
And now of course these values are the ones that we
specified here instead of the default values.
Now,
one thing that's really cool about the default values is
that they can contain any expression.
For example, we could do *1.2, for example,
then we would get this here.
Okay.
But what's even more useful is that we can actually use the
values of the other parameters that were set before it.
So here we can now say that the price should be calculated
based on the number of passengers.
All right.
So if we now do this, create booking again,
just some random flat number here,
let's say again, two
but then with five, we will get another value.
So indeed you see 398.
So the number continues down here and then 995
And so the price is now dynamically calculated by default,
based on this value we specified and to the number of
passengers. And again,
this only works for parameters that are defined in the list
before this one.
So this would not work because JavaScript basically
specifies these parameters in orders and as it reaches.
So right now, as it reaches the price,
it doesn't know about the number of passengers yet.
And so that wouldn't work.
Now, another thing that's important to note here is that we
cannot skip arguments here when we called a function.
So for example,
let's say we wanted to leave the number of passengers as the
default value, but then specify the price.
So we cannot do this.
So skipping the number of passengers now,
and then only specifying a new price.
So if we do this,
then of course the number of passengers becomes a 1000
because the second argument here will always be mapped to
the second parameter.
So if we wanted to leave this one year at a default,
there is a nice trick.
So the number of passengers we can simply set to undefined,
alright,
and this works again because setting the parameter to
undefined,
it's the same thing as not even setting it, remember?
So when we don't set a parameter
so when we don't pass an argument into that parameter,
then it will take the value of undefined.
And so specifying undefined here is exactly the same.
And so this is how we basically skip a default parameter
that we want to leave at its default.
And so now, as I reload it here,
you see that number of passenger is still one.
And indeed the price is now, 1000.
Okay. So yet another very nice addition
to the language in ES6 here
and pretty straightforward to understand too.
So see you in the next video.
関連動画をさらに表示
CDS View with input parameters Part 7 ABAP on HANA Course
Functions | Godot GDScript Tutorial | Ep 13
ES6 #1: Spread & Rest Operator in ES6 in JavaScript in Hindi | Technical Suneja
Python Tutorial for Beginners 8: Functions
JSX | Mastering React: An In-Depth Zero to Hero Video Series
Fast API Tutorial, Part 3: Query Parameters
5.0 / 5 (0 votes)