Check out bidbear.io Amazon Advertising for Humans. Now publicly available 🚀

Javascript: Conditional Statements & Logical Operators

Intro

The basic groundwork of logical functions. Comparing values, evaluating truthfulness of statements and doing different things based on those results.

Comparison Operators

Assuming x=5

Operator Name Example Result
> Greater Than x>10 false
>= Greater than or equal to x>=5 true
< Less than x < -50 false
<= Less than or equal to x <= 100 true
== Equal to x == “5” true
!= Not equal to x != b true
=== Equal value and type x === “5” false
!== Not equal value or type x !== “5” true

The reason that == is true and === is false is because of “type coercion”. Because 5 is a number and “5” is a string, they have an equal value but not an equal type. With == Javascript uses type coercion to realize that even though they have a different type they have an identical value and therefore are the same at this level of specificity.

This gets a bit tricky when comparing null and undefined. For example if we have:

var x = null

x == undefined //true

x === undefined //false

Some additional interesting cases

true == "1" // true

0 == false //true

null == undefined //true

NaN == NaN //false

NaN is Not A Number

Logical Operators (AND, OR, NOT)

Assuming x = 5 and y = 9

Operator Name Example Result
&& AND x < 10 && x !== 5 false
` ` OR `y > 9
! NOT !(x === y) true

Truthy and Falsy Statements

The easiest way to evaluate whether something is truthy or falsy is to evaluate it by turning it into the simplest possible Boolean Logic statement. An easy way to do that is to just negate it with !

negating a statement with !

In this example a simple string of text would be true. In the first evaluation we are saying that it’s not true that “test string” is true, which is false. By using the double !! we can simply flip it into a more readable format to see if the statement is falsy or truthy.

There is not a solid logic behind whether these things are falsy or truthy, this is just a quirk of the language and it is different in different languages.

Here is a full set of examples that Javascript finds either Truthy or Falsy

truthy falsy samples in console

Some interesting things to note:

  • A text string that has characters is truthy
  • An empty text string is falsy
  • null and undefined both falsy
  • 0 is falsy but every other integer is truthy, positive or negative!
  • NaN is falsy! (notice in my screenshot I forgot the double !! for NaN)

If, Else If, Else

When we combine the logical operators with If statements we are able to make conditional statements that give us different outputs depending on our inputs. For example if we want to make a conditional statement for whether we should let someone into a concert venue that serves alcohol depending on their age we could make the following:

var age = 20

if (age < 18) {
  console.log("No Minors Allowed")
} else if (age >= 18 && age <= 20) {
  console.log("go in but no drink")
} else {
  console.log("Have fun!")
}

And then when the variable age is changed the output in the console will change to reflect the new status.

On thing to note on this conditional statement is that the first part of the else if statement is redundant, because if the age was less than 18 the code would have executed on the first if statement anyways.

Additionally, if we wanted to figure out if the persons age was odd or even, we can use the Modulo (%) mathematical operator. We simply divide any number by two with modulo and the answer will either be equal to zero or it will not. If the answer is equal to zero the number is even. If it is not then the number is odd. All even numbers are perfectly divisible by two without any remainder. We can use this as a simple check if a number is even or odd.

var age = 16

// If age is odd
//(not evenly divisible by two)
if (age % 2 !== 0) {
  console.log("Your age is odd!")
}

// If age is a perfect square
if (age % Math.sqrt(age) === 0) {
  console.log("Your age is a perfect square!")
}

As you can see we used a similar concept to check whether the age is a square root, with one of Javascripts built in math functions.

As a final example here is a simple guessing game:

var secretNumber = 55
var numberGuess = prompt("What is your guess?")

if (numberGuess < secretNumber) {
  console.log("Too Low!")
} else if (numberGuess == secretNumber) {
  console.log("You got it!")
} else {
  console.log("Too High!")
}

As a quick note, inputs that are entered with the prompt command are counted as strings, even if you are inputing numbers. So when we are checking if the guess is equal to secretNumber we would want to use == instead of ===.

typeof variable

If you want to check the datatype of a variable you can just check it with a built in function typeof, and then the name of the variable

var dogName = "Stewie"

typeof dogName //string

Switching datatype – Number(variable)

If you want to convert an integer that is in string format to a number you can simply wrap it in a built in datatype switcher

var myAge = "31"

typeof myAge //string

typeof Number(myAge) //number

and in the console we try it out…

changing myAge variable from string to number

perfect!

Amazon Ad Analytics For Humans

Advertising reports automatically saved and displayed beautifully for powerful insights.

bidbear.io
portfolios page sunburst chart