Skip to content

Instantly share code, notes, and snippets.

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

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 kid, 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 kid, 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'
  • 32
  • 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 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 new condition.

var age = 22;

if (age < 21) {
  console.log('Sorry kid, 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 kid, 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 the expression evaluates 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 kid, I can't serve you");
  return;
};

serveDrink();

In the above example 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 kid, 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);
  return debriefAgent();
}

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

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]
@danielafcarey
Copy link

I think the line numbers are right? Hopefully...

  • line 3: "tell Javascript, 'If this, then that.'"
  • line 7: "open that gate for the right people"
  • line 20: I don't know if you meant to put evaluates in backticks? Maybe if you want to accentuate the use of the word, bold or italics? I also think this sentence could be less jargony - "execute the console.log" sounds stiff..."So we log 'Sorry kid, I can't serve you.' in our console" is a little lighter?
  • line 24: "can use"? or "must use"? Might be more clear to say you have to use a bool in a conditional. Also you introduced ternaries but don't have an example or explanation of what it is so that could be confusing. (Edit after reading through the whole gist - I see that you talk about them later, so maybe say something like "More on that later" here?)
  • line 28: Those don't seem like "common" truthy values - those two examples are actually pretty tricky truthy values, haha. Also this might be a cool spot to add an interactive part to the lesson and have students play in their dev tools to test various values and whether they are true or false.
  • line 58 (and below in the examples): should be less than, not less than or equal to...if someone is 21 they should get serveDrink, right?
  • line 67: This sentence is worded so that I can't understand what it's saying. I think you might mean something like, "Operators are used in comparison expressions and return true or false"?
  • line 92: you say "What happens" twice
  • line 94: extra comma after reference; also this is a good, concise explanation of this tricky thing
  • line 98: This example is a little confusing. After reading the next section it makes more sense that you want everyone to have water so that's why it's in the "else" but I think in terms of code, you wouldn't actually put something like this in an else condition - you would just add it separately from the conditional if you wanted to always serveWater(). Semantically, it is confusing because you expect if/else if/else conditions to be independent of each other (no overlaps) but in this example, someone who is age <= 21 will not get water (because they'll be evaluated in the if block), someone over 21 will not get water (because they'll be evaluated in the else if block), so who will get the water? Someone whose age variable is set to something other than a number, I think. (I just had to double check that this was right and it seemed to work that way in my console...every age input that was a number would hit either of the first two blocks but anything other than a number made the else execute). So I think typically, you want to make sure your conditional expressions are all based on the same variable type (in this case it would be the age integer). Also depending on if you adjust something here with this example, it could mean you should update the Return section below
  • line 107: You're missing an opening bracket after the else and a closing bracket after.
  • line 131: might also be good here to give a kind warning about over-using ternaries. They can sometimes make the code harder to read because someone is trying to be too clever.
  • line 169: I didn't know this - this is cool!

Overall it's great! Just a few questions and places I think you could clarify or maybe use a different example?

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