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.
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.
[]
{}
'strings'
32
true
''
null
undefined
0
NaN
false
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();
}
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.
&&
||
!
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
.
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.
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 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.
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?
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.
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');
Write me a dry filter
function that returns only the truthy
values.
const arr = [NaN, '', false, 'blink-182', {}, 0, 532, true]
I think the line numbers are right? Hopefully...
this
, thenthat
.'"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?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 theif
block), someone over 21 will not get water (because they'll be evaluated in theelse if
block), so who will get the water? Someone whoseage
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 theReturn
section belowOverall it's great! Just a few questions and places I think you could clarify or maybe use a different example?