Unit 2, Lesson 3

$\textbf{Conditionals in Node.JS}$
$\text{Written by:} $
$\text{Jacob Levine, Class of 2020}$
$\text{Last Revised: March 2020}$

Like any other language, JS has ways to run code based on the value of statements, called conditionals. JS implements conditionals in 3 main ways: if/elif/else, which evaluates code based on the truth value of bools (booleans), switch/case/default, which simplifies long if chains when looking at the value of one variable, and try/catch, which handles errors that may occur in a line of code.

Comparison Operators

In general, when using bools for conditionals, you’re usually going to get them from comparing two things of similar datatypes (comparing two variables, comparing a variable with some other statement, comparing a property of an object with some statement, etc.) or looking for something inside something else (check if something is inside an array, etc.) The first part is usually achieved with comparison operators. There are 8 that concern us:

==

This operator checks if two variables are equal, but does not check their data type.

In [1]:
console.log(5 == '5')
true
In [2]:
console.log(5 == 5)
true
In [3]:
console.log(5 == 5.1)
false

!=

This operator checks to see if two variables are not equal in value, but does not check their datatype. Will return the opposite of ==

In [4]:
console.log(5 != '5')
false
In [5]:
console.log(5 != 5)
false
In [6]:
console.log(5 != 5.1)
true

===

This operator checks if two variables are equal, AND checks their data type.

In [7]:
console.log(5 === 5)
true
In [8]:
console.log(5 === '5')
false
In [9]:
console.log(5 === 5.1)
false

Note: JS has only one “number” datatype, but other languages usually have different datatypes for integers and decimals (floats). Some also have different datatypes for different sizes of ints and floats, so in JS 5 === 5.0, but this may not be true in other languages.

!==

This operator checks if two variables are not equal OR if they are of different types. Note that this returns the opposite of ===, not ==.

In [10]:
console.log(5 !== 5)
false
In [11]:
console.log(5 !== '5')
true
In [12]:
console.log(5 !== 5.1)
true

>

This operator checks if the left part is greater than the right part. Returns true if and only if the part left of the > is strictly greater than the part to the right. If they are numbers, it looks at numerical value. If the two values are strings, it looks at alphabetic order. If the two values are arrays, it compares each place until either one array is done or there is a difference. Note that some things cannot be compared: there is no way to compare “hi” to 5, for example. > will return false in both attempted comparisons

In [13]:
console.log(3 > 2)
true
In [14]:
console.log("hi" > "person")
false
In [15]:
console.log(2 > 3)
false
In [16]:
console.log(["hey", "what's", "up"] > ["hey", "what's", "down"])
true
In [17]:
console.log("up" > "down")
true
In [18]:
console.log(2 > "hi")
false

<

This operator checks if the left part is less than the right part. Returns true if and only if the part left of the < is strictly less than the part to the right. Behaves the same way as the above > operator.

>=

This operator is the same as >, but will also evaluate to true if the two sides are equal.

<=

This operator is the same as <, but will also evaluate to true if the two sides are equal.

Logical And/Or/Not

Sometimes you don’t want to use the direct evaluation of one statement and instead want to combine multiple bools into one for your use. JS has 3 operators that can help:

The logical and &&

Will return true if and only if the bools on the left and the right are true. Note the use of short-circuiting behavior: if the part on the left is false, the part on the right won’t be evaluated.

In [19]:
console.log(3 < 7 && 4 > 2)
true
In [20]:
console.log(3 >= 7 && 4 > 2)
false
In [21]:
var a = 2;
var b = 5;
console.log(a == b && a == x) //doesn't throw an error even though x isn't assigned because right is short-circuted
false

The logical or ||

Will return true if and only if the bool on the left is true or the bool on the right is true. Note the use of short-circuiting behavior: if the part on the left is true, the part on the right won’t be evaluated

In [22]:
console.log(false || true)
true
In [23]:
console.log(false || false)
false
In [24]:
var a = 2; 
console.log(a != 3 || a >= x) //doesn't throw an error even though x isn't assigned because right is short-circuted
true

The logical not !

Will return the opposite of what is fed in

In [25]:
console.log(!false)
true
In [26]:
console.log(!true)
false

A note about these operators

They don't actually require boolean input! They operate based not on what is exactly equal to true or false, but what is equivalent to true or false. In brief, 0 (in all its forms), "", null, undefined, and NaN are all equivalent to false (these are called "falsey" values), while all other numbers and strings are equivalent to true (these are called "truthy" values). Thus, the following statements are valid:

In [27]:
console.log("hi" || "no")
hi
In [28]:
console.log(2 && 7)
7
In [29]:
console.log(2 && 0)
0
In [30]:
console.log(! 8)
false
In [31]:
console.log("" || "hi")
hi
In [32]:
console.log("" || "")

if/else if/else

These are perhaps the most basic statements in programming. Note the same type of short-circuiting behavior as discussed above:

In [33]:
var a = 5;
var b = 10;
var c = 0;
if (a > b) {
    c = 5; //is not run; would be run if a = 12
} else if (b == a + 10) {
    c = 7; //is not run; would be run if a = 15
} else if(b > a+2) {
    c = 2; //is run
} else if(a == 5) {
    c = 3; // is not run because statement above was, even though
           // a does in fact equal 5.
} else {
    c = 1; // is not run; would be run if a = 9.
}
console.log(a)
console.log(b)
console.log(c)
5
10
2

The conditional operator ?

One nice way to do the equivalent of if/else in one line is the operator ?. A statement using ? usually looks like: x = y ? a : b; where y is a boolean statement. If y is true, then x will be set to a, otherwise it will be set to b. Note that only one of a or b will be evaluated when run.

In [34]:
2 > 3 ? 5 : 7
Out[34]:
7
In [35]:
4 >= 4 ? "hi" : "no"
Out[35]:
'hi'

switch/case/default

Often, you will want to run code blocks based on the value of a variable. We can do this with if/else if/else as below:

In [36]:
var a = 3;
if (a == 1){
    a += 2;
} else if (a == 2) {
    a += 3;
} else if (a == 3) {
    a -= 1;
} else {
    a = 1;
}
console.log(a)
2

However, this looks inelegant. switch/case/default allows us to do this much more simply:

In [37]:
var a = 3;
switch(a) {
    case 1:
        a += 2;
        break;
    case 2:
        a += 3;
        break;
    case 3:
        a -= 1;
        break;
    default:
        a = 1;
        break;
}
console.log(a)
2

Note that switch/case/default does not short-circut by default, so if you want to exit the switch statement after a case, you need to add the break keyword to the end of your case

Practice Exercises

  • Create a statement equivalent to || using ?
  • Create a statement that returns the minimum of two numbers using ?
  • Create a statement that returns a string saying if someone is old enough to drive or to vote in Illinois
  • Create a statement that returns "3" if an input is 3, "4" if an input is 4, "nice" if an input is 69, and "no" otherwise
In [ ]: