Step 5: If/Else Statements
Now we're going to start adding in some logic. So far we have been logging the same thing every time we run the code, but what if we want to log different things according to different conditions? In programming there is something called an "if/else statement". It tests conditions, and will perform different actions based on the outcome of these tests.
The structure of an if/else statement in JavaScript is as follows:
It basically translates to:
"if this condition is true, do this - or else do something else"
Try it out
What if we want to console.log()
"Hello world!" if we're feeling happy, and something else if we're sad?
Let's define a variable called happy
, and assign it a boolean value of true
or false
(depending on how happy you're feeling).
Then let's write our if/else statement. In our condition, we want to test if the variable happy
is equal to true
. Note that in JavaScript, to test if two things are equal you need to use a triple equals (===
) rather than just one (=
). Read more about that here if you're curious.
Now let's add in what will happen if the conditions are met. The comments are there to explain what is happening.
Now run this code (not forgetting to put the variable at the top of the Repl), and see what happens! Try changing the value of your variable from true
to false
.
Mini challenge
Write an if/else statement that evaluates if a string has more than 10 letters. If it does, it will print the string 'this is a long word!'
, and if it has less than ten letters, it will print 'this is a short word'
. Once you have it working, try it with different words to check you get different results.
To find out the length of a string, you can use the .length
method. For example:
To find out if a number is bigger than 10, you can use the >
operator, which checks if one number is greater than another. More information on operators here.
Here's a skeleton to get you started:
Last updated