Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jeremiahjstanley/5223e97df5a0d991f3e8e21920b8bf36 to your computer and use it in GitHub Desktop.
Save jeremiahjstanley/5223e97df5a0d991f3e8e21920b8bf36 to your computer and use it in GitHub Desktop.

Conditionals

Conditional let us determine when we do what

Using conditionals allows us to protect code from executing until the proper conditions are met.

Think of conditionals a way of putting a wall around a walled city. Your city has a gate, but you hold the power to open that gate from the right people.

Let's look at an example:

var age = 18

if (age < 21) {
  console.log('Sorry kid, I can't serve you')
}

In this example, we are comparing two numbers, if age is less than (<) 21 we execute the console.log within the brackets. In the age the expression age < 21 evaluates to true, so we execute the console.log. This brings us to our next concept.

Truthy and Falsy Values

In JavaScript we a boolean data types that are explicitly true or false, but JavaScript assigns everything a truthy or falsy value. In if blocks and ternaries we can use truthy and falsy values as conditions

Let's go over some common truthy and falsy values in JavaScript.

Truthy Values

  • [] - empty arrays
  • {} - empty objects

Falsy Values

  • '' - empty strings
  • null
  • undefined
  • 0
  • NaN

Adding a Second Condition

Let's look at our expample from before with some minor changes.

var age = 22

if (age < 21) {
  console.log('Sorry kid, I can't serve you')
}

In this example our initial condition isn't met, let's add an else if block to handle this condition.

var age = 22

if (age < 21) {
  console.log('Sorry kid, I can't serve you')
} else if (age > 22) {
  serveDrink()
}

Ternaries

Type Coercion

In general, type coercion is one of those handle with extreme caution sort of things that JavaScript lets you do. There are two types of cercion

Boolean Coercion

Did you know that there's a nifty feature in JavaScript that allows you coerce any value into a boolean. It's super handy and it's called the double bang or !!

Let's look at an example.

var 

if (!! ) {

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment