JavaScript Conditional Expressions

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Professional Modern JavaScript Lessons

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36

JavaScript Conditional Expressions

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

Expressions vs Statements

let a = 123;
const b = a;
const c = b + a;

if (true) {
console.log('The truth is out there');
console.log('This is... the X-Files');
}

const condition = Math.random() < 0.5;
let value;

if (condition) { value = 'Head' } else { value = 'Tail' }

// ERROR: expression expected
value = if (condition) { 'Head' } else { 'Tail' };

Ternary Conditional

const condition = Math.random() < 0.5;

const value = if (condition) { 'Head' } else { 'Tail' }; // ERROR: expression expected

const value = condition ? 'Head' : 'Tail'; // Okay 🫂

console.log(condition, value);

Function Simple Returns

function getFee(isMember) {
return isMember ? 2 : 10;
}

console.log(getFee(true)); // 2
console.log(getFee(false)); // 10

function getBeverage(age) {
return age >= 21 ? 'Beer 🍺' : 'Juice 🧃';
}

console.log(getBeverage(30)); // Beer 🍺
console.log(getBeverage(14)); // Juice 🧃

Combine with Destructuring

let weather, lower, upper, head;

lower = weather === 'warm' ? 'shorts' : 'jeans';
upper = weather === 'warm' ? 'shirt' : 'sweater';
head = weather === 'warm' ? 'cap' : 'beanie';

[lower, upper, head] = weather === 'warm'
? ['shorts', 'shirt', 'cap']
: ['jeans', 'sweater', 'beanie'];

Nested Conditional

function nature(num) {
return (
num === 0 ? 'zero'
: num > 0 ? 'positive'
: 'negative'
);
}

console.log(nature(0)); // 'zero'
console.log(nature(3)); // 'positive'
console.log(nature(-5)); // 'negative'
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

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.

Professional Modern JavaScript

Professional Modern JavaScript

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36