Conditional with Else
for CSCI E3, Harvard University author(s): Larry Bouthillier
by DustyWhite
HTML
WEEK 4 : Lesson 1 - EXAMPLE 2<b>Be sure to open your console to see the output of this code.</b>
<ol>
<li>Notice the '==' symbol on line 6. When we're testing values in an expression, the double equals sign '==' is a comparison operator. It's different from single equals '=', which assigns values. Note the difference:
<pre><code>x = 6 // this assigns the value 6 to the variable x
x == 6 // this tests to see if the value of x is 6, and evaluates as <b>true</b> or <b>false</b></code></pre>
Refer to the textbook, p133-136 for a full explanation of comparison operators. (We'll also cover these in detail in the next Lesson in Canvas)</li>
<li>
In this example, we are checking to see if we need to make the word 'bananas' in our output plural. Note: This is not the most elegant way to do this particular task, but it illustrates a basic conditional.
</li>
</ol>
JavaScript
"use strict"
var numBananas = prompt("How many bananas");
// we'll see if this number should have a plural or singular
if (numBananas == 1){
console.log("You have "+ "a" +" banana");
}else{
console.log("You have "+ numBananas +" bananas");
}