(woodwind music) - From here on, we're gonna try to do before and after comparisons. So what I'm gonna really do is just actually split my screen here. And we'll try to have a before and after of each of these features that we've discussed. So, we'll start by talking about this kind of scenario which is a function that receives a parameter that we want to give essentially some kind of default value to.
And you've probably seen something kind of like this. Anybody seen that before? Using the or operator. This is kind of referred to as the default value idiom or the default parameter idiom. Usually you see that at the top of the function so you see one of those lines for each one of the parameters that you want to give some default value to. Now, if we, for example pass in something like foo without anything we know X is gonna end up as 42. But what happens if we pass in foo of zero? Does X end up as zero or does it end up as 42? - [Man] 42.
- If you aren't really aware yet of what's going on with your operator, it does a truthy test on the first argument, on the first operand. And if it's true, or truthy, it returns that operand. Otherwise it returns the other operand. So zero is a falsy value, meaning that it will fail and end up returning the 42 value. So we can't affirmatively pass in something that's falsy like zero, null, undefined, et cetera. So really, technically, the long form, the not cheating form of this is to say, if X is not equal to undefined, then use X, otherwise, use the default value.
That's really how you write the full version of that default value idiom. So if we pass in zero now, of course we're gonna get zero. If we pass in null. If we pass in foo without anything we get 42. If we also pass in undefined, we're still gonna get 42. So undefined in this case becomes the empty value and everything else, including null, becomes an actual affirmative value that we care about. Undefined means I'm not passing anything here.
So in this case, if we pass in foo of zero, we get zero. If we pass in null, we get null. If we don't pass in anything, we get the 42. If we pass in undefined, we also get the 42. What do you think happens if I do this? Foo dot apply don't care about my this. What happens if I apply an empty array to the arguments list of foo? What's X gonna be? 42. What happens if I apply one with an empty slot in it? - [Man] 42 - Still gonna be 42.
In all those cases, we end up effectively passing in undefined which then triggers the default algorithm. So, pretty straightforward. We now have the ability to declare our default values.
This course was created by Frontend Masters. It was originally released on 01/10/2017. We're pleased to host this training in our library.
- The arrow function
- Arrow function variations
- Closures and explicit blocks
- Default values
- Using the gather and spread operators
- Dumping variables
- Concise properties and methods
- Symbols, iterators, and generators
- Optimizing codes for the reader