Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jeremiahjstanley/a8c8380d49c8c58164d941d59957bc2a to your computer and use it in GitHub Desktop.
Save jeremiahjstanley/a8c8380d49c8c58164d941d59957bc2a to your computer and use it in GitHub Desktop.
Conditionals Lessons

Conditionals

Conditionals let us determine when we do what - it's the way you can tell JavaScript: "if this then that"

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

Think of conditionals as a way of putting a wall around a castle. The castle has a gate, and you have the power to open that gate for the right people.

Let's look at an example:

var age = 18;

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

In this example, we are comparing two numbers. The variable age is assigned the value 18. 18 is < (less than) 21, so the expression evaluates to true, So we log 'Sorry bud, I can't serve you.' in our console. This brings us to our next concept.

Truthy and Falsy Values

In JavaScript, we have the boolean data type which are values that are explicitly true or false, but JavaScript assigns everything a truthy or falsy value. In if blocks and ternaries (we'll get to these in a bit) we must use truthy and falsy expressions as conditions.

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

Let's open our consoles and explore some truthy and falsy values.


Truthy Values

  • []
  • {}
  • 'strings'
  • 42
  • true

Falsy Values

  • ''
  • null
  • undefined
  • 0
  • NaN
  • false

Adding a Second Condition

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

var age = 22;

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

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

var age = 22;

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

Comparison and Logical Operators

In an expression, comparison operators compare values and return true or false.


  • >
  • <
  • >=
  • <=
  • ==
  • ===
  • !==

Logical operators can be used to combine multiple boolean expressions or values and provide a single boolean output.


  • &&
  • ||
  • !

A Common Gotcha

Let's consider these two arrays.

var arr1 = [1, 2, 3, 4, 5];

var arr2 = [1, 2, 3, 4, 5];

They look identical, yes?

What happens when we ask JavaScript if they are === to each other?

What's going on, they're literally the same. This has to do with how JavaScript assigns primitive data types by value while complex data types are assigned by reference. In the example above arr1 and arr2 reference different objects and are therefore not strictly equal.

Adding an Else

At the end of an if block you can add a catch-all condition by writing the else keyword. The else keyword doesn't require an expression because its execution is not dependent on an expression evaluation.

var age;

if (age < 21) {
  console.log('Sorry bud, I can't serve you');
} else if (age >= 21) {
  serveDrink();
} else {
  console.log('You've gotta show me an ID if you want a drink pal');
}

In this example age is undefined - we cannot compare a defined value to undefined, so our expressions evaluate to false and our else is executed.

The Return Keyword

JavaScript requires the keyword return when you want your code to stop executing. Let's look at an example where it would be important to use the return keyword.

var age = 20;

if (age < 21) {
  console.log("Sorry bud, I can't serve you");
  return;
};

serveDrink();

In the above example, we want to stop the execution of our function if our patron is underage. If we didn't employ the return keyword we would always execute serveDrink()

Ternaries

Ternaries allow you to pose JavaScript a yes or no question. With if blocks you can have multiple else if's but ternaries only have two possible outcomes.

Let's take our example from above and refactor it as a ternary.

var age = 22;

age >= 21 ? serveDrink() : console.log('Sorry bud, I can't serve you');

Ternaries are typically more succinct and lighter on syntax.

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 coercion. There is explicit and implicit coercion. For now, let's focus on implicit coercion. The loose equality operator == handles comparison and type coercion when necessary.

Let's look at these two examples:

console.log('7' === 7);

console.log('7' == 7);

What are some use cases for implicit type coercion?

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 secretAgent = {
  name: 'James Bond',
  codeName: '007',
  agency: 'M16',
  clearance: 'eDV'
};

if (!!secretAgent.clearance) {
  console.log(!!secretAgent.clearance);
  debriefAgent();
  return;
}

In this example, we have our secretAgent object with four properties. One of these key values pairs is clearance: 'eDV'. The string 'eDV' is truthy in javascript and the !! literally coerces that value to a boolean.


A final exercise.

Mod 1 Folks

Write me an if block (or ternary if your feeling up to it!) that evaluates if the currency your provided is right side up.

var dollarBill = {
  faceUp: true
};

function vendingMachine(currency, selection) {
  if (condition) {
    console.log(`Dispensing your ${selection}`)
  }
};

vendingMachine(dollarBill, 'Granola Bar');

Mod 2 Folks

Write me a dry filter function that returns only the truthy values.

const arr = [NaN, '', false, 'blink-182', {}, 0, 532, true]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment