In this lesson you will learn what what is short circuiting in JavaScript. After we will go straight to one of the most popular use cases of it - providing a default fallback values for potentially not defined returns.
Dimitri Ivashchuk: [00:00] Short-circuit operators are the logical operators && and ||, utilizing their short-circuit quality. If we try to log(true && true), it's important to know that logical operators are being executed, or the expressions are executed from left to right. First this one is executed, and then only if it's true, or truthy, it will execute the second part. This is the short-circuit quality.
[00:33] If we change it to false, you immediately see that it returns false without evaluating the second part of the expression. The same works for || operator, but a little bit different because || operator is a little bit different. If we try to put false as the first value, it will omit calling this value and it will directly jump to the second value.
[01:06] Both these cases bring us a lot of possibilities to use them in JavaScript to ease our lives.
[01:13] The first case would be, let's say we are creating an object which would have a name, Dimitri, and age of 24. Then, let's say we want to get a name variable from there, so displayedName = object.name, and we console.log(displayedName). We see Dimitri here.
[01:51] Let's say we have forgotten to provide such a key to this object, or let's say our API call has been not successful and we didn't get the data that we have expected. In this case, name is undefined. You see it here. Most likely, your application will break if you leave it like that. What we could use? || operator for declaring a default value.
[02:23] You could already see that it evaluated instead of undefined, to default, which happens straight, like in this case. Let's get and explain it. Object.name is undefined, which is falsy. False value will just omit it and short-circuit it to the next value, which is true, and will display the second value.
[02:55] In our case, it's a string of "default", and it will display default.