JavaScript If Else Statements and Best Practices

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 If Else Statements and Best Practices

Subscription Required

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

Basics

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

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

Single Statement Body

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

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

Early Return

let birthday = (person) => {
if (
!person
|| person.age === null
|| person.experience === null
) return;

person.experience += 10;
person.age++;
}
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

A key tenant of programming languages is the ability to branch to different execution parts based on the condition and the simplest way to achieve that in JavaScript is with if L statements. Consider the simple example of a function where based on a pasta number, we want to determine if we should store the string positive or negative within a result variable. This is where we can use if else conditions. First off, we check if the number is greater than not equal to zero, and if it is, the result is positive. Otherwise, we are going to store the string negative and eventually return the result from our function. For an IF statement,

00:33

we have the IF keyword followed by a conditional expression and if that expression evaluates to a bully and true, then the IF block is going to execute. Otherwise, the statements within the LS block are going to execute. Let's run through this function with two simple examples. First, you pass in a value three, which of course is greater than or equal to zero. Therefore result is going to be positive and that is what gets returned. If you pass in a value like negative five, which is not greater than or equal to zero is going to fall into the LS block and result is going to be negative and that is what gets returned. Now one thing to note about if LS within JavaScript is that the LS is actually

01:09

completely optional and in this particular case we can even rewrite this example without using an ls. We utilize the fact that within the IF condition, we don't necessarily need to assign to a variable that we are going to return anyways. Why not just write the return statement within if this means that the remaining code within the nature function is not going to execute, essentially turning everything outside of the IF condition into a giant L. Of course we can also verify this by passing in the same examples of nature three, returning positive and nature minus five, giving us the string negative. An additional thing to know about if LS within JavaScript is that we can chain

01:44

additional if statements joined to an L. Let's expand our example to support an additional use case of providing the string zero when the number is equal to zero. Here, in addition to if and Ls, we have an LIF within our function, so when the first condition turns out to be false, we do an LS if and then do a check for the second condition. And if that is also false, then eventually we go to the final L statement. So if you pass in zero, the first condition is true, we get zero. If you pass in a positive number, the second condition is true and we get positive. And similarly,

02:18

if you pass in a negative value, then the first condition is going to be false and the second condition is going to be false and we eventually get back the string negative. If you only have a one statement in an F or an L code block, you can actually skip using the brackets around the body, but be careful not to overuse it as it can lead to subtle bugs. So we can actually rewrite our last example to be simple. If LSE and L statements each in their own line where the code blocks are not surrounded by girl brackets and of course this code is still correct, it works exactly how you would expect.

02:51

Now let's talk about some of the hazards of doing something like this. Consider this seemingly harmless function that takes two values, A and B. If A is equal to one and if B is equal to two, then it should log out A is one and B is two. And if A is not equal to one, then it should log out. A is not one to prove that I'm not lying to you. I will pass in a check value one and two, and indeed this will log out. A is one and B is two. Now here's the question. If I pass in one and three, what do you think it is going to log out? This will actually log out A is not one,

03:24

and that statement is clearly wrong because A is one. What has happened here is that I lied about not lying. The L block is actually associated with the second if and not the first. If and if I format it to its correct place, you can see that the console log statement is actually incorrect. Someone wrote poor code. The console log statement that makes sense for this particular L would be A is one and B is not two. And of course now everything makes sense since tower scape is mostly white space agnostic. It's a good idea to use brackets to clarify your intent. In fact,

03:59

we can rewrite the original code to be much better if we use brackets and you can immediately see that if the intent was for A is not one to be associated with the first F, it looks much better with the brackets in place. Another advantage of using the curly brackets within your if N L blocks is that they allow you to pass in multiple statements. For example, in this particular function, if you pass in the password abra, Debra, it'll print all of these lyrics on the console. If you pass in the wrong password, you get nothing pass in the magic word and you get, every time you call my name,

04:35

I heat up like a burning flame. Let's create a different song, but this time without the curly brackets, and I'm going to lie again over here and say that this is perfectly fine. If you pass in false, we should get nothing yet we do get everything after the first statement because without a code block, only a single statement is a part of the if so, the who and let's go still execute because they're not associated with the if in any way. So my final tip for this section would be that if you do want a single statement with your if or your Ls, write it after the if on the same line and enter a new line afterwards. Just to be very clear,

05:11

a common trick that developers use when working with conditional blocks and functions is early return statements. And this can help your code look prettier and make it easier to understand. Consider a simple function called worthy that is designed to take a person object, and if a valid object is passed in and it has an age property that is not null and it has an experience that is not null, then we want to update the experience by 10 and the age by one. Instead of this nested. If we can rewrite it into three simple early return statements, if there is not a person we return, if the age is null will return. If there is no experience,

05:45

we return and now we can be guaranteed that the person has an experience and an age that we can update. And of course we can go one step further and combine all of these different conditions into a single if Expression. If you don't have a person or the person age is null or the person experiences null, then we simply do an early return. Otherwise, we update the experience and the age. I hope you enjoyed this tutorial. As always, thank you for joining me and I'll 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