JavaScriptProgrammingBeginner GuideWeb Development

Javascript: Conditionals + Comparison and Logical operators

By Ezequiel Carrizo
Ezquiel, the author Picture
Published on
A image of a computer with JavaScript code in the screen

Today I want to cover a little bit about conditional statements, comparison operators, and Logical operators in JavaScript. as this will set the fundamental concepts that will allow you control the flow of the programs you will write.

Remember: my objective is to keep it simple so you can start practicing programing, you will be gaining more advanced knowledge as you practice. At the end of this article I will add additional sources you can consult to continue learning more about today's topic.

Conditional Statements

In the previous post, we covered a little about Conditional Statements with a hands on example. Today, we will go a little deeper on it and showcase a few more scenarios that you can try on your own.

Conditional statements allow your program to make decisions based on certain conditions. The most common conditional statements are if, else if, and else, and today we will cover these. Follow the links if you want learn about Switch Statement and Ternary Operator.

0. Understanding block statements

Often referred "block", A block statement is defined by a pair of curly braces `{}` it serves as grouping that allows the statements to be treated as a single unit. Any number of statements can be enclosed within these braces.

{
// Block starts
let x = 10;
console.log(x);
x += 5;
console.log(x);
// Block ends
}

Hi there! Want to support me?

1. if statement

Using the if statement you can execute the code inside the block only when the specified condition is true.

if (1 === 1) {
// block executed, the condition is true (one is equal one)
console.log('One is equal one');
}
if (1 === 0) {
// Block not executed, the condition is false (one is not equal zero)
console.log('One is Equal Zero');
}

Try this code in the playground!

2. else statement

The else statement, always used after a if/elseif executes when all other conditions are not met, Let's extend the example from above adding an else statement to review how it works

if (1 === 1) {
// Block executed, the condition is true
console.log('One is equal one');
} else {
// Block not Executed, prior condition met, block is skipped.
console.log('One is not equal one')
}
if (1 === 0) {
// Block not executed, the condition is false
console.log('One is Equal Zero');
} else {
// Block executed, non-prior condition met so this code is run instead.
console.log('Zero is not equal One')
}

Try this code in the playground!

3. elseif statement

The elseif statement, provides a way to handle multiple conditions in a sequence and ensures that one and only one block of code is executed based on the first true condition encountered

// The output of this program will be "Condition number 3 met"
// because 1 === 1, is the only condition that returns true
if (0 === 1) {
// block skipped, condition is false
console.log('Condition number 1 met');
} else if (25 === 0) {
// block skipped, condition is false
console.log('Condition number 2 met');
} else if (1 === 1) {
// block executed, condition is true
console.log('Condition number 3 met');
} else {
// block not executed, prior condition met.
console.log('No prior condition met, else executed');
}

Try this code in the playground!

Comparison Operators

We use comparison operators to compare values within the code, you are familiar with them already I have been showing it you in the code examples. Until now, we used the strict equal comparison operator or ===, let's take a look at them all :

  • === Strict equality (checks both value and type)
    1 === 1 // is "True" because number 1 is equal number 1
    1 === '1' // is "False" because Number 1 is not equal to string '1'

  • !== Strict inequality (checks both value and type), opposite of strict equality
    1 !== 1 // is "False" because number 1 is no different to number 1
    1 !== '1' // is "True" because Number 1 is not equal to string '1'

  • < Less than, used to compare numbers
    5 < 10 // is "True" because 5 is lesser than 10
    15 > 10 // is "False" because 15 is not smaller than 10

  • > Greater than, used to compare numbers
    15 > 10 // is "True" because 15 is Greater than 10
    5 > 10 // is "False" because 5 is bigger than 10

  • <= Less than or equal to
    5 <= 5 // is "True" because 5 is equal to 5
    3 <= 4 // is "True" because 3 is lesser than 4
    6 <= 4 // is "False" because 6 is Greater than 4

  • >= Greater than or equal to
    5 >= 5 // is "True" because 5 is equal to 5
    6 >= 4 // is "True" because 6 is Greater than 4
    3 >= 4 // is "False" because 3 is lesser than 4

  • == and != Loose equality and loose inequality, It compares two values after converting both to a common type (type coercion), I'm leaving this to the end because it can be a little confusing, I recommend you to restrict yourself to strict equality and inequality for now and use Loose Comparison only for checking if values are true or false I'll create a separate article about this comparison operator another day.
    5 == '5' // is True
    '' == 0 // is True
    false = 0 // is True
    false == 'false' // is False
    false == '' // is True
    false == null // is false

Logical Operators

Logical operators are used to combine multiple conditions. The most common logical operators are && (AND), || (OR), and ! (NOT).

AYour first programing bad joke, if (!false), it's funny because it's true
if (!false), it's funny because it's true

Logical AND (&&) Operator

The && operator returns true only if both operands are true. If the first operand is false, the second operand is not evaluated (short-circuit evaluation).

Example: Checking Eligibility for a Discount

the payment system can provide discounts only if "client is a member" AND "purchase is over $50.00"

// In our code, member is True and purchaseAmount is 60,
// Meaning that both conditions are true
let isMember = true;
let purchaseAmount = 60;
if (isMember && purchaseAmount > 50) {
console.log('You are eligible for a discount.');
} else {
console.log('You are not eligible for a discount.');
}
// Change these values in the playground and see it working!

Try this code in the playground!

Logical OR (||) Operator

The || operator returns true if at least one of the operands is true. If the first operand is true, the second operand is not evaluated (short-circuit evaluation).

Example: Checking for Opening Hours

A store is open if it’s either Monday or if it's the weekend (Saturday or Sunday).

// Day is "Saturday", so, day === 'saturday' is true
let day = 'Saturday';
if (day === 'Monday' || day === 'Saturday' || day === 'Sunday') {
console.log('The store is open.');
} else {
console.log('The store is closed.');
}

Try this code in the playground!

Logical NOT (!) Operator

The ! operator inverts the boolean value. If the operand is true, it returns false, and if the operand is false, it returns true.

Example: checking for a power on/off of a tv

Indicate when the TV is turned on

let isTVOn = false; // Represents the state of the TV
if (!isTVOn) {
console.log('The TV is not turned on. Please turn it on.');
} else {
console.log('The TV is already on.');
}

Try this code in the playground!

Explanation:

  • isTVOn is false, meaning the TV is off.
  • The logical NOT operator ! inverts the value of isTVOn. So, !isTVOn becomes true because !false is true.

Good Job!

You have learned about conditional statements, comparison operators, and logical operators in JavaScript. You can now start writing more complex programs that can make decisions based on certain conditions. if you have any questions, feel free to ask!

Stay curious, and happy coding!

Continue reading more about JavaScript in my Posts and visit the following sources

Hi there! Want to support me?