DEV Community

Jason Park
Jason Park

Posted on

A Beginner’s Guide to Javascript Operators and Conditional Statements

Contents

Introduction

Whether you are a seasoned professional or just starting your journey as a software engineer, one of the first major concepts you will learn is conditional statements. Conditional statements are blocks of code that allow you to be able to control certain actions. Simply put, it helps your program make decisions based on certain information. Every conditional statement contains one or more tests, typically involving the use of relational and logical operators. Before diving into how conditional statements work, we must first understand the relevant relational and logical operators that compose these statements.

This guide is for those who are just getting started with Javascript. If you are still confused after reading this guide, please read more about these topics in detail at the MDN website. All links are listed in the Resources section.

Relational operators

Relational operators compare two values and return either true or false based on the operator. All of these require two variables, each on opposite sides of the operator. Below is a table of the relational operators.

Operator Name Use Example
> Greater than Returns true if first value is greater than second value
1 > 3
// false
< Less than Returns true if first value is less than second value
1 < 3
// true
>= Greater than or equal to Returns true if first value is greater than or equal to second value
3 >= 3
// true
<= Less than or equal to Returns true if first value is less than or equal to second value
5 <= 3
// false
=== Strict equality Returns true if both values equal each other (no type conversion)
‘hello’ === ‘hello’
// true
!== Strict inequality Returns true if both values do not equal each other (no type conversion)
‘3’ !== ‘3’
// false
== Loose equality Returns true if both values equal each other after type conversion
3 == ‘3’
// true
!= Loose inequality Returns true if both values do not equal each other after type conversion
3 != true
// false

Table 1: Relational Operators

The difference between the strict and loose operators is that the strict operators will only return true if the two values are equal to each other without any type conversions. On the other hand, the loose operator attempts to convert the values into the same type before making the comparison. Since the behind-the-scenes conversion creates more room for errors and bugs, it is best practice to use the strict operators as default over the loose operators.

If you get to a point where you need to check between two values of different types, I recommend converting them into the same type yourself before using the strict operator to compare. It is important to also note that comparing values of different data types using relational operators may yield unpredictable results. This is yet another reason to make sure that the two values being compared are of the same data type before comparison.

Logical operators

Logical operators can be broken down into two types: unary (one variable) and binary (two variables). The unary operator has one variable to the right of ! and the binary operators have a variable on both sides of the operator. Below is a table of the logical operators.

Operator Name Use Example
!
(unary)
Not (or Bang) Returns the opposite boolean
!3
// false
&&
(binary)
And Returns the first value if it is falsy; otherwise return the second value
0 && false
// 0
||
(binary)
Or Returns the first value if it is truthy; otherwise return the second value
undefined || ‘hello’
// ‘hello’

Table 2: Logical Operators

! converts the value into a boolean (if it isn’t one already) and returns the opposite boolean value. Remember that all values are truthy except for:

  • false
  • undefined
  • null
  • NaN
  • 0
  • “” or ‘’

In addition to its uses shown on the table, all three logical operators can be combined inside conditional statements to produce more elaborate tests. This will be shown in more detail in the following sections.

Conditional operators

A conditional operator returns one of two operands depending on the result of the conditional test. Another name for this is the ternary operator (or ternary expression).

Operator Name Use Example
condition ? ifTrue : ifFalse 
Ternary Returns ifTrue if condition is true; otherwise return ifFalse
let x = 1
x > 0 ? x + 3 : x
// 4

Table 3: The Conditional Operator

The ternary operator works the same as a simple if and else statement. So if we can just use if and else statements to accomplish what the ternary operator can do, why bother with it? The answer is conciseness. Traditional if and else statements will take up more lines than ternary expressions and for that reason, some may opt for this shorthand version in certain cases.

Conditional statements

Conditional statements combine the relational and logical operators to create a conditional test. Similar to the basic conditional operator, the conditional statement helps manage the flow of certain actions.

if, else if, else statements

As the heart of Javascript conditionals, the if statement is a versatile tool that helps developers control a certain conditional behavior. When combined with else if and else, it can cover most, if not all, conditional situations. The set-up for these statements are specified below.

if(condition1) {
  // execute if condition1 is true
} else if(condition2) {
  // execute if condition1 is false and condition2 is true
} else {
  // execute if previous tests are false
}
Enter fullscreen mode Exit fullscreen mode

In the code block above, we have one if, else if and else statement. This suggests that there are three possible outcomes: condition1, condition2 and none of the above. You can add as many else if statements after the if and before the else if there are more outcomes. The else if and else statements are optional but in order to use them, you need an if statement in the beginning.

I mentioned earlier that && and || can increase the complexity of conditional statements. This is done by combining one or more conditional tests to generate a single multi-step test. We will start with the and operator, &&.

As its name implies, the and operator is used as a two part test. In order to pass the overall test, one must pass both individual conditions. If any one of the two conditions fail, the overall test will also fail.

const x = 5;

if(x > 0 && x < 3) {
  // code1
} else if(x > 5 && x <= 10) {
  // code2
}
Enter fullscreen mode Exit fullscreen mode

The first condition tests if x is greater than 0 and if x is less than 3. If these conditions are fulfilled, we execute code1 in the first if statement. If not, we move on to the next conditional test. This one checks if x is greater than 5 and less than or equal to 10. Since x = 5, it doesn’t pass either conditions and neither code1 or code2 is executed.

We can think of || in a similar way but with the word “or” instead of “and.” There are two conditions and if one or the other passes, the entire condition passes.

const x = 3;

if(!x || x !== ‘hello’) {
  // code1
}
Enter fullscreen mode Exit fullscreen mode

If !x equals true or x does not strictly equal ’hello’, we run code1. In any other case, we run code2 inside the else block. Since x equals 3, !x (or !3) equals false (all numbers are truthy and ! switches the truthiness of the variable). Moreover, x does not equal ’hello’, as it is assigned to 3. Because one of the two conditions results in true, we pass our overall test and code1 is executed.

switch statements

A switch statement contains an expression that is matched against each case value via strict equality. One at a time, it goes down each case until it finds a match. Once it does, it starts the execution from that case. If there isn’t a break keyword, the execution falls through and runs the block of code inside the next case, even if the case value doesn’t match. This process repeats until it meets break or checks every succeeding clause. The syntax is as follows:

switch(expression) {
  case value1:
    // execute if expression matches value1
  case value2:
    // execute if expression matches value2
    break
  default:
    // execute if expression doesn’t match value1 or value2
}
Enter fullscreen mode Exit fullscreen mode

The break and default keywords are optional: the point of break is to cease the automatic fall through and immediately stop; default is there so it runs when there is no other match or when the execution reaches it from falling through.

const x = 3

switch(x + 1) {
  case 3:
    // code1
  case 4:
    // code2
  case 5:
    // code3
    break
  default:
    // code4
}
Enter fullscreen mode Exit fullscreen mode

We start with x equals 3. The switch expression is x + 1, which equals 4. Starting from the top, there is no match until it reaches case 4. It proceeds to run code2 then falls through to case 5. Even though this isn’t a match, code3 is executed. The break at the end of case 5 stops the execution from falling through to default.

switch statements are more situational than if statements. They are most commonly utilized when there are many else if or else statements that need to be matched through strict equality (===).

Conclusion

In the preceding sections, we discussed the role of relational and logical operators within the context of conditional statements. After reviewing all the pertinent operators, we explored how if, else if, else and switch can cover almost every conditional test with the right combination of operators and statements.

It is an understatement to make the claim that conditional statements are important in programming. Even beyond the scope of software development, it plays a crucial role in our everyday lives. “I will go on a walk if it doesn’t rain” or “if I plan on going out tomorrow night, I will do my homework tonight” are some real life examples of conditional statements that we set for ourselves, sometimes without even thinking about them. With this in mind, it is paramount that novice software developers have a solid grasp on this concept before trekking forward in their new and exciting career.

This guide is meant to serve as a learning tool for people who are just starting to learn Javascript (and coding in general as these concepts apply to other languages beyond Javascript). Thank you for reading and if you have any questions or concerns about some of the material mentioned in this guide, please do not hesitate to contact me at jjpark987@gmail.com.

Resources

Top comments (0)