DEV Community

Laura Jane
Laura Jane

Posted on

Operators/Conditional statements: if (youUnderstand) {'Great!'} else {'Read on'}

First of all, let me just apologise for the blog title layout..
How else was I going to grab your attention and help you to understand Operators and Conditional Statements?


This is my 4th blog post on DEV, I am beginning to write about what I have learned, or gone over again, as it really helps me to learn and embed the fundamentals, whilst also helping others on their journey!

This article is covering the basic Operators, and Conditional statements in JavaScript.

Alt Text

Conditional statements... Is that you?..

Every day we are making decisions, it could be an easy one like wether to have a tea or a coffee, or an unpopular one for example, wether or not to deploy on a Friday. We call these in Javascript, If, else statements: If we decide to have a coffee, then we would make one and enjoy, if not we would opt for the tea. A conditional statement checks certain conditions, and then executes the code accordingly based on these conditions.

What happens IF?...

Firstly, lets talk about IF statements, think of these as the top layer of a cake, and as we dive into else and if else statements - these will become our other layers..

We often base our decisions (or conditions!) on something simple, if its Monday, we might work, or if we are tired, we may take a break and rest. In JavaScript, we can execute this based on a condition. see an example of an if statement below:

Alt Text

else if, else if.. Im confused!

Its completely ok to be confused as you begin learning about conditional statements - They are quite tricky to learn to begin with, the else if statement always comes before the else statement (This is our reliable statement.. You will find out why when you reach that section!) These statements are the middle layers of our cake, you can add as many of them as you like, to make your code as easy, or as complex, as you'd like. This is an example of an else if statement:
Alt Text

Anything Else?

Actually yes, there is.. else statements, these are added to an if statement, so that if the condition within an if statement, resolves to false then this block of code will execute instead - We could call it a reliable statement (should all your previous code render false- you know you have always got a statement to fall back on!)
Here's an example:
Alt Text

Hello... This is your operator, how may I help you?

There are three types of operators we can use for Conditional statements These are:

Logical Operators
In Javascript, when we work with conditional statements we use values that are Boolean - This means that the value will either be 'True' or 'False'. There is a certain operator that work directly with these values, this is known as a Logical Operator there are 3 we can use:

&& - The and operator: This operator checks that both conditions are true. when using this operator, both statements must be true resulting in the block executing and therefore printing to the console, however, if either condition is false the condition will overall render false and result in execution of the else block.

|| - The Or operator: This operator allows for a bit more flexibility in conditions, it allows for any of the statements within a code block to be true in order to successfully execute and print to the console.

(!) - The Not operator: Also known as the bang operator, this takes a true value, and passes back a false value - to put it simply, it returns the opposite of what is intended to be printed to the console.
Below is an example of Logical operators in action:
Alt Text

Comparison Operators

These are pretty self explanatory, and quite straightforward to use in conditional statements, there are 6 types of this operator.
These work by comparing the values from left to right.

< - Less than
> - Greater than
<= - Less than/or equal to
>= - Greater than/or equal to
=== - Is equal to
!== - Is not equal to

Ternary operator

A ternary operator simplifies an if..else statement like below, these can be used for conditions which return either true or false:
Alt Text

True or false... Tough call!

In this section Im going to talk about truthy or falsy values So we have talked about boolean values, so what about non-boolean types? Good question!
Sometimes you might just want to check if a particular variable exists, but not actually assign it a value.

So let's look at non-boolean types

Non-boolean types include:

  • Strings
  • Numbers

Alt Text

Take the above conditional statement - the if statement will execute as the of the variable slicesOfPizza will return true as it has been given a non-falsy value.

Which values are falsy? Lets find out!

  • - 0
  • - Empty strings like "" or ''
  • - null which means there is no value at all
  • - undefined - when a variable isnt given a value
  • - NaN or Not a Number

The second statement will return false as it's value is an empty string! Yipee - Looks like your getting that dog!
Hooray for that particular empty string huh?

Truth or false assignment... Yes really!

Pssst, If you bring together what you know so far about logical operators - I will let you in on a little secret. There is a shortcut you can use! JavaScript will assign a truthy variable to the value if you use the or operator which if you remember is the || syntax.

Remember, statements check the left condition first!
Heres an example:
Alt Text

Switch statements

else if statements are great if we want to check more than one condition. - Thats great but surely there must be a shorter way to write these condtions you say?

Your totally right - they are called switch statements

A switch statement give us an alternative syntax than we can use to check multiple conditions and keeps our code looking clean and readable, helping us identify bugs or syntax errors quickly to resolve them.
Example below:
Alt Text

The break keyword instructs our computer to stop running the code block and to exit, meaning the computer wont continue to check for any more cases or execute any futher code within that block, without the break keyword the code will continue to run without breaking, meaning all blocks of code will run regardless or wether they are correct.

Conclusion... Yes finally!

This is just a basic summary on conditional statements and operators, it is always best to keep practising in order to understand these, but articles definitely help too!

If you made it this far... Thank you so much!

Follow me on Twitter: @miss_lorsx for updates on new blog posts coming soon!

Top comments (5)

Collapse
 
vonheikemen profile image
Heiker

I want to share a tiny bit of trivia I learned last year. Here I go: It turns out there is nothing special about the combination of else if.

If you write an if or an else statement without curly braces it will only "apply" to the next statement. So this is valid.

if(1 > 1) 
  console.log('What?');
else 
  console.log('Duh!');

So is this.

if(1 > 1) console.log('What?');
else console.log('duh!');

When we do this.

if(1 > 1) {
  console.log('What?');
} else if(1 == 1) {
  console.log('Of course');
}

In here it just so happens that the else is followed by an if, which (I think) is technically only one statement.

We could do this (but we shouldn't).

let lesson = 'cool';

if(lesson == 'learned') {
  console.log('I deserve a break');
} else while(lesson == 'cool') {
  console.log('Ooohhh');
  lesson = 'learned';
}

We could also have: else switch, else for, etc...

Again, don't do this at home, or work, or in side projects or anywhere. It's just a funny thing javascript can do.

Collapse
 
arnoldgee profile image
Arnau Gómez • Edited

Thank you very much for that fun and comprehensive explanation! I find real joy in reviewing elementary concepts and seeing them on a new light. Also love those PolarCode snippets!

If you want to get better at javaScript, try javascript.info/ Do you know it? It provides in-depth explanations if you want to learn even more about operators and their perks.

Btw anyone can explain me why [] == [] is false in javascript?

Collapse
 
sargalias profile image
Spyros Argalias

Hi Laura, thanks for the great article. It's quite thorough and explains the concepts very well.

The only thing I found challenging was that to check the code I had to write it by hand myself. That's fine if that's what you intended, but otherwise you can make the code be text rather than an image by wrapping it in triple backticks (more information here.

Keep up the good work :)

Collapse
 
misslorsx profile image
Laura Jane

Thank you for your feedback -

I will bear that in mind for future reference, I’m just trying to keep everything clean rather than attempt to go into different ways. It was just an example. Thank you. Have a great day!!

Collapse
 
bdougieyo profile image
Brian Douglas

Great post! Keep it up