Default Parameters | JavaScript đŸ”„ | Lecture 119

The Coding Classroom
27 Apr 202309:17

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

00:00

🔱 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.

05:00

🧭 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

Default parameters are values that are pre-assigned to function parameters, allowing the function to be called without passing those arguments. This concept is introduced as a new feature in ES6. In the video, default parameters are used in a booking function for an airline, where parameters like number of passengers and price can have default values if not explicitly provided when calling the function.

💡Short Circuiting

Short circuiting refers to a technique used with logical operators (&&, ||) in JavaScript, where the second operand is not evaluated if the result can be determined by the first operand alone. This is demonstrated in the video as a way to implement default parameters before ES6, by assigning a value to a parameter only if it is falsy (undefined).

💡Enhanced Object Literals

Enhanced object literals are a feature in ES6 that simplifies the creation of objects by allowing property values to be derived from variables with the same name. In the video, this syntax is used to create a booking object, where properties like flightNum are directly assigned from parameters with the same variable name.

💡Strict Mode

Strict mode is a way to enable a stricter variant of JavaScript, eliminating some silent errors and throwing exceptions for potentially unsafe actions. The video script mentions that strict mode is already enabled from the start, ensuring a more secure coding environment.

💡Array Methods

Array methods, like push() in the video, are built-in functions that allow manipulation and operations on JavaScript arrays. In the video, the push() method is used to add new booking objects to a bookings array, serving as a data structure to store all bookings for the airline.

💡Expressions in Default Parameters

One of the powerful features of ES6 default parameters is the ability to use expressions as the default value. The video demonstrates this by setting the default price as a calculation based on the number of passengers (price = numPassengers * 199). This allows for dynamic default values.

💡Parameter Order

The order of parameters in a function definition is important, as it determines the mapping of arguments to parameters when the function is called. The video highlights this by showing that a default parameter can only access the values of parameters defined before it in the parameter list.

💡Skipping Arguments

In some cases, it may be desirable to skip providing an argument for a particular parameter when calling a function, allowing it to take the default value. The video demonstrates a technique for skipping arguments by passing undefined as the argument value, which is treated the same as not providing an argument at all.

💡ES6 (ECMAScript 2015)

ES6, also known as ECMAScript 2015, is a major update to the JavaScript language that introduced many new features and syntax improvements, including default parameters. The video contrasts the ES6 approach to default parameters with the older, more verbose ES5 way of achieving the same functionality.

💡Function Parameters

Function parameters are the named variables defined in the function declaration that act as placeholders for values to be passed into the function when it is called. The video focuses on using default values for function parameters, specifically in the context of a booking function for an airline.

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

play00:01

Let's start this section about functions

play00:04

with one of the easiest parts, which is default parameters.

play00:10

And a new section means new starter files.

play00:13

So as always, get yours from the Gitup repository and then

play00:17

open them up in your VS Code.

play00:20

So as always, we already start with strict mode here

play00:24

but now let's talk about default parameters.

play00:27

So sometimes it's useful to have functions where some

play00:31

parameters are set by default. This way

play00:35

we do not have to pass them in manually in case we don't

play00:39

want to change the default.

play00:41

Now in this section,

play00:42

we're gonna to continue with the airline theme that we

play00:45

started by the end of the last section.

play00:48

And so let's now create a very basic booking function and

play00:52

we're gonna to do that,

play00:53

starting with the knowledge that we already had previously.

play00:59

So without the default

play01:02

parameters first,

play01:06

so just a normal function and into this function,

play01:09

we need to pass in the flight number,

play01:12

the number of passengers

play01:16

and the

play01:18

price.

play01:20

And then let's simply use this data to create an object and

play01:24

push that into some bookings array.

play01:29

So booking,

play01:31

and now here we can use the enhanced object literal syntax

play01:35

that we learned about in the previous section.

play01:38

So we cannot create an object with a flight num property

play01:42

without having to do this, remember?

play01:46

So we simply defined a variable here and that will then

play01:49

create a property with this name and also the value that's

play01:53

in the variable.

play01:57

And then let's just log it to a console.

play02:01

And then let's just create an array out here which will

play02:05

contain these bookings.

play02:08

So we start empty here then we simply push them each

play02:11

time there is a booking.

play02:13

So basically for the airline to keep

play02:16

the bookings in some kind of

play02:17

system.

play02:19

And this is all very fictional.

play02:22

It's just to show you the default parameters in this case.

play02:26

And speaking of that,

play02:28

based on what we learned in the last section about

play02:30

short circuiting, how would we implement default parameters?

play02:35

Well,

play02:36

let's start by calling this function without specifying some

play02:39

parameters and see what we get then.

play02:43

So create booking.

play02:45

And now with just the flight number, let's say LH 123,

play02:51

and now we need a new terminal as always.

play02:59

So again, I hit tap here

play03:01

to auto complete the operation.

play03:09

And indeed here is our browser with our page already

play03:13

running.

play03:14

Now here's some kind of problem.

play03:17

Oh, and that's because we called this booking here,

play03:20

the same as the array.

play03:22

And so here it is then trying to push this object into

play03:25

itself basically.

play03:28

So we need to create bookings here, giving it a new name.

play03:33

And so indeed now we get here the result of this object,

play03:38

and now it works.

play03:39

And here we see the result of this booking object.

play03:44

And so what we wanted to see here was that the numPassengers

play03:48

and the price are set to undefined because we didn't specify

play03:52

them.

play03:54

And so now we can use short circuiting to our advantage

play03:57

because we know that these are falsy values.

play04:01

Okay.

play04:03

And what I'm doing here is basically the old way of setting

play04:06

default parameters,

play04:07

just to remember how it would work before ES6.

play04:11

So let's say I wanted to set the number of passengers to one

play04:16

by default.

play04:17

So basically we would reassign this parameter like this.

play04:23

So numPassengers is numPassengers or one,

play04:28

which is the default value.

play04:31

And this works because of the reasons that we learned in the

play04:33

last section, which is that whenever this is a falsy value,

play04:38

which undefined is,

play04:39

then the result of the

play04:41

OR operator here will be this second operant.

play04:44

So this value here in this case one,

play04:48

and now we can do the same thing with the prize.

play04:53

Let's say 199 is the default price.

play04:57

And so if we reload this now,

play05:00

then indeed we get our default values here.

play05:03

Okay. So coming from this part of the code, however,

play05:07

this is a lot of ugly boilerplate coat. And again,

play05:12

this is the ES5 way of doing it.

play05:15

So I will take this out.

play05:17

Let me actually, write

play05:19

ES5 here because now in ES6 there is a better way.

play05:23

So all we have to do is to write this equals one.

play05:28

And so now this here will be the default value

play05:32

and the same for the price.

play05:34

Let's say to 199.

play05:36

And now if we reload, then we get the same result here.

play05:40

And this here of course, looks a lot nicer and is

play05:43

a lot more intuitive to read.

play05:47

Now, of course we can override these defaults.

play05:50

Otherwise this wouldn't make much sense.

play05:53

So let's try

play05:56

H 123, and now for

play05:59

two passengers, and let's say 800.

play06:05

And now of course these values are the ones that we

play06:07

specified here instead of the default values.

play06:11

Now,

play06:12

one thing that's really cool about the default values is

play06:15

that they can contain any expression.

play06:18

For example, we could do *1.2, for example,

play06:22

then we would get this here.

play06:25

Okay.

play06:26

But what's even more useful is that we can actually use the

play06:29

values of the other parameters that were set before it.

play06:34

So here we can now say that the price should be calculated

play06:38

based on the number of passengers.

play06:40

All right.

play06:42

So if we now do this, create booking again,

play06:47

just some random flat number here,

play06:51

let's say again, two

play06:53

but then with five, we will get another value.

play06:58

So indeed you see 398.

play07:01

So the number continues down here and then 995

play07:06

And so the price is now dynamically calculated by default,

play07:10

based on this value we specified and to the number of

play07:13

passengers. And again,

play07:15

this only works for parameters that are defined in the list

play07:19

before this one.

play07:21

So this would not work because JavaScript basically

play07:25

specifies these parameters in orders and as it reaches.

play07:30

So right now, as it reaches the price,

play07:32

it doesn't know about the number of passengers yet.

play07:35

And so that wouldn't work.

play07:38

Now, another thing that's important to note here is that we

play07:41

cannot skip arguments here when we called a function.

play07:45

So for example,

play07:46

let's say we wanted to leave the number of passengers as the

play07:50

default value, but then specify the price.

play07:54

So we cannot do this.

play08:00

So skipping the number of passengers now,

play08:04

and then only specifying a new price.

play08:07

So if we do this,

play08:08

then of course the number of passengers becomes a 1000

play08:13

because the second argument here will always be mapped to

play08:16

the second parameter.

play08:18

So if we wanted to leave this one year at a default,

play08:21

there is a nice trick.

play08:23

So the number of passengers we can simply set to undefined,

play08:27

alright,

play08:29

and this works again because setting the parameter to

play08:32

undefined,

play08:34

it's the same thing as not even setting it, remember?

play08:36

So when we don't set a parameter

play08:39

so when we don't pass an argument into that parameter,

play08:42

then it will take the value of undefined.

play08:45

And so specifying undefined here is exactly the same.

play08:49

And so this is how we basically skip a default parameter

play08:52

that we want to leave at its default.

play08:56

And so now, as I reload it here,

play08:58

you see that number of passenger is still one.

play09:01

And indeed the price is now, 1000.

play09:04

Okay. So yet another very nice addition

play09:08

to the language in ES6 here

play09:10

and pretty straightforward to understand too.

play09:13

So see you in the next video.