If you already have a subscription, you can sign in.
Enjoy free content straight from your inbox 💌
00:00
Before we can truly understand the JavaScript ary operator, we need to understand the difference between statements and expressions. Developing a mental model for what is an expression is quite easy. Basically whatever you can use on the right hand side of an assignment statement is an expression within JavaScript. So here the right hand side 1, 2 3 is an expression. Similarly, we can assign variable A to variable B, so the variable by itself is an expression. We can assign B plus A to another variable, which means that B plus A is also an expression. Now code within chows script essentially executes in statements.
00:34
All of the three things that we have over here, the three variable declarations are actually variable declaration statements. Lots of things within JavaScript are statements. For example, if is also a statement and it consists of a body which then again consists of multiple statements. Hey, we have two console log statements. Now consider a simple use case where we calculate a condition based on math at random, which has a 50% chance of being true based on the result of this condition. We want to create a value which will either be head or tail, like a coin toss. Of course we can use an IF statement for this purpose. If the condition is true,
01:10
we assign value to head otherwise be assign value to tail. Now sadly, within JavaScript, if statements are not expressions, which means that we cannot sort of write this kind of code where we assign value to the result of the if conditions, if block or else block, this will actually result in an error quite aptly called expression expected. When the result of your FLS conditional decision is going to be an expression, you can actually replace that FL statement with the conditional operator. The conditional operator consists of three operas, a conditional expression, and if expression result and an else expression result.
01:46
The first two operas are separated by a question mark and the second two operas are separated by a colon. When the condition expression values is too true, the conditional operator resolves to the IF expression, otherwise it resolves to the else expression and we can do a quick demo in this particular case by logging out the condition and the final value, you can see that when condition is true, we get head and when condition is false we get, and that is the basics of the conditional operator. Depending upon the circumstance, the conditional operator can greatly decrease the velocity of your code when
02:20
compared to an if elf, for example, consider this array of items consisting of numbers 1, 2, 4, 10, and three, and we want to find the max item within this array without using the built-in math module. When you want to go through an array of items and compress them down into a single result, that is a great use case for the array reduce function that we have looked at in a previous lesson. We start off by assuming that we will see nothing and initialize our max to minus infinity, and then for each iteration we check the current max value, which is going to be present within the accumulator and compare it to the
02:53
current. And if current is greater, then we found a new max and return that as the new accumulator. Otherwise, we continue with the accumulator that we already have no surprise, the final accumulator value is going to point to the maximum, which in this array is going to be 10. Using the conditional operator, we can actually invert this FLS to put the return in front and then based on current being greater than accumulator, either return current or the accumulator and converting our body into single return statement opens up an additional opportunity for a cleanup. When the body of an error function is a single return statement,
03:28
we can actually get rid of the code block, get rid of the return keyword and the return is automatically implied. And if you run this code, you can see that it is functionally still correct. It is returning that value 10, but it reads much better. You can see that if current is greater than accumulator, then we have a new max, otherwise continue with the accumulator that you have. A great mental model to have with the conditional operator inspired by functional programming is that it is a simple way to map a single value into one of two possible results. For example, hey we have a simple function called get fee,
04:01
which returns a different value based on the IS member bullion. For members, we map the fee to two and for non-members we map it to 10. Similarly, we can get a beverage based on the user's age. For example, if the person has an age of 30, we give them beer. And for younger members, for example, age 14, we default to juice. When you want to update multiple variables based on the same condition, a pattern that you can use is to combine the conditional operator with JavaScript D structuring to do it all in one go. Consider the use case where based on the weather,
04:34
we want to determine our lower upper and head gear. Of course, based on the weather we can make our decision in three separate statements. We either go with shorts or jeans for the lower shirt or sweater for the upper and cap or beanie for the head. Now it's not particularly hard to read and I will be completely okay with this, but it doesn't immediately present the fact that based on the same condition we are making three different choices and there is a pattern of repeating ourself twice. Using already structuring, we can do it all in a single statement based on the weather. We can create an array that consists of three items,
05:08
either for the warm weather or the cold weather and then assign them to lower upper and head in a single destructuring pattern. Not saying that the new structure is miles better, but it is worth knowing. A common pattern that you will find with the conditional operator is the nested turnery. And it sounds like it would be messy, but when formatted correctly it can look like a thing of beauty. Consider a simple function that determines the nature of a number. If the number is equivalent to zero, we return the string zero. If it is greater than zero, we return the string positive, otherwise we default to negative.
05:40
So for zero we get zero for three we get positive. And for minus five we get negative. We can actually replace this if return else. If return else return into a single return of a nested ary expression. No surprise, it is functionally the same as The code that we had before. And the first time that you see code like this, you might be a bit taken aback, but there is a way to read it. You read it like the first statement is an if the last statement is the final else. And everything between is an L. If if you write your nester turn like this, there are quite easy to understand.
06:16
But if you do it all in one line, don't be that person. Nobody can understand what the hell is going on over here. So the pattern to follow is to have the first if on its own line, the last else on its online and in between as many lines as the else safe expressions that you need. A common mistake that beginners make when using the conditional operator is not knowing the impact of operator precedents. Fortunately, there is a simple fix for this issue without having to do mental gymnastics, consider the desire to build this format, discount function, which takes a value and then based on a bullion is percent either as a percent
06:52
or the dollar sign as a suffix. Now we can actually write this function quite easily. We will take a value and an is percent and then add to the value based on is percent the suffix percent or the dollar sign. Now this looks perfectly fine and we might probably approve this in a code review, but when we run this you can see that we actually only get the person signed for both of our format discount calls. And the reason behind this bug is operator precedents the eternity has a very low priority, which means that whenever we write an expression like this as far as the runtime is going to be concerned,
07:24
you can pretty much think of it as the individual expressions being wrapped by brackets. So let's take a look at that expression in our return statement and wrap it up in brackets. And I think you can see the issue now in this particular case, value plus is percent is going to value to truthy and therefore we are going to map that to the person signed by itself, which is the result that we are seeing. And the fix is pretty simple. Whenever you have a conditional, as a part of a bigger expression, wrap up the whole conditional with brackets so that that conditional evaluates before anything else. With this simple fix in place, if you run the core again,
07:59
you can see that we get the results that we expected. Alternatively, don't use a conditional as a part of larger expressions and instead pre-compute it into its own variable that you can then use in the latter expression. And as a code reviewer, make a mental note that the turny should either be wrapped or stored in their own variables. Fun fact, conditional is the only turny operator in the DAOs programming language that is the only operator that has three operas, which are the condition if and else expressions. And sometimes people including myself, just call it the turn operator. As always, thank you for joining me and I will see you in the next one.