Mastering the use of conditions is one of the 5 fundamental skills of building algorithms:
Conditions are the only way developers have to tell the computer how to make decisions in real time, very similar to how our brains work.
Let's say we are building a program to help us pick what to wear and we hate the color blue. We can tell the computer to avoid blue using a condition like this:
If color is not blue, then... do something.
Else... do nothing or exit.
The previous example was a simple condition, but in real life picking what to wear involves a combination of several conditions to make the final decision, for example: Let's look at this algorithm that tells if you have a flu.
Basically, this algorithm has two variables to consider:
Our job as developers is to sit down and try to prepare a strategy and come up with an algorithm that solves a problem.
Another way to write the algorithm is to combine two questions in the same condition using the
&& for AND and
|| for OR:
As you can see here we are using
else if together for the first time, for faster coding. Another trick you can use for faster coding:
|instead of ||you write |
|instead of ||you write |
<Greather Than or Lower Than Operators
In the particular case you are comparing numbers, to find out if one of the compared numbers is greater or lesser than the other:
Another great trick for faster coding is using ternaries that basically allow us to code everything in just one line:
In this example the variable
flu will only be true if
youWereHitByTrain==false at the same time. If that question is not true, then
flu will be false.
Ternaries are being used A LOT these days because they save you a lot of time and we will also be able to use them later in jsx code (React).
Another important use of conditionals is to generate HTML based on certain conditions. For example, let's say that we have a bootstrap alert that we are about to render into the website:
If we want this alert to show only if the user is younger that 16 years old we could do something like:
alertHTMLCode variable will be empty if the user age is greater than 16, if it's less it will contain the entire HTML.
The most efficient way to learn: Join a cohort with classmates like yourself, live streamings, coding jam sessions, live mentorships with real experts and keep the motivation.
From zero to getting paid as a developer, learn the skills of the present and future. Boost your professional career and get hired by a tech company.
Start a career in data science and analytics. A hands-on approach with interactive exercises, chat support, and access to mentorships.
Keep your motivation with this 30 day challenge. Join hundreds of other developers coding a little every day.
Start with Python and Data Science, Machine Learning, Deep Learning and maintaining a production environment in A.I.