- Notifications
You must be signed in to change notification settings - Fork0
License
thecodeaftermath/skills-based-javascript-intro-to-flow-control-js-intro-000
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
- Write
if
statements in JS - Write
if
-else if
-else
statements in JS - Use the ternary operator in JS
- Write
switch
statements in JS
Sometimes, we only want to allow the execution of code under certain conditions.
Think of it this way. When you're driving a car, you can only go through a lightif the light is green.Otherwise, if the light is yellow, you prepare to slow down; and if the light is red, you stop. Notice that we have distinct cases that we want to check for.
In programming, when we check for a statement in this way, we check to see whether the statement istrue
orfalse
. JavaScript, being the friendly language that it is, usestrue
andfalse
directly to mean exactly what they say.
The example above might be written, in pseudo-JavaScript (for once, this won't work in the browser console), like this:
if(lightIsGreen){go()}elseif(lightIsRed){stop()}elseif(lightIsYellow){slowDown()}
When we get down to it, everyif
statement like the above is saying, "If the thing in the parentheses istrue
, then do what's between the curly braces."
But before we dive in toif
statements, how do the things in parenthesesbecometrue
orfalse
?
JavaScript lets us compare things. Most of these comparisons come straight from math: we can ask if something is less than something else (enter these in your console!):
3<5// true3<2// false3<3// false3<10000000// true'alpha'<'beta'// true (!)
We can ask if something is greater than something else:
5>-1// true5>5// false20>30// false'gamma'>'beta'// true (!)
We can even ask if something is less-than-or-equal-to something else:
20<=30// true20<=20// true20<=10// false
or greater-than-or-equal-to something:
5>=5// true5>=1// true5>=10// false
How do we test if something isexactly equal to something else? We know that we can't just use=
, because that's how we assign values to variables. Instead, we need to use===
:
5===5// true4===5// false'5'===5// falseparseInt('5',10)===5// true
Top Tip: Sometimes you'll see only==
for comparison in JavaScript. It's best to use===
, as the former will try tocoerce values in order to compare them, meaning that it's not always comparing what itsays it's comparing!
We can string together these comparisons using&&
(pronounced "and") and||
("or"):
5===5&&10<11// true5===6&&10<11// false5===5&&10<9// false4>5||20<=20// true4>5||20<19// false4>3||20<19// true
With&&
,both statements (to the left and right of&&
) must betrue
in order for the entireexpression (that is, the entirephrase) to betrue
; with||
, only one of the statements needs to betrue
.
Keep in mind that JavaScript reads these combinations from left to right, returns the last statement it saw, and only evaluates as many statements as necessary. So if we write,
5===5&&1
JavaScript won't returntrue
, it will return1
. If instead we write,
5===4&&0
JavaScript will returnfalse
, because it stops evaluating the&&
expression (again, this just means the entire phrase of comparisons) on its first false encounter. Similarly, if we write,
200<100||'alphabet'
JavaScript will return 'alphabet', because it needs to evaluate the right-hand side of||
(since200 < 100
isfalse
). But if we write,
200>100||'treasure'
JavaScript simply returnstrue
— it doesn't even check the right-hand side of||
.
JavaScript lets us control what blocks of code to execute usingif
statements,if
-else
statements,if
-else if
-else
statements, ternary operators, andswitch
statements.
You'll be writing your code inflow-control.js
. Make sure to run the tests usinglearn
.
if
statements look like this:
if(something){// do something}
They work as the name implies:ifsomething
istruthy (so the booleantrue
or anything other than the empty string (''
),0
,null
, orundefined
), the code in between the curly braces runs; if not, the code between the curly braces is skipped.
Now, inflow-control.js
let's write a function calledbasicTeenager
that accepts an age as a parameter. The function should contain an if-statement that checks to see if the age is a teenager. If the age is between 13 and 19, return"You are a teenager!"
You will often see anif
statement used in combination with anelse
clause. Anelse
clause will only get executed if the previousif
statement is falsey.
Syntax:
if(conditionToTest){// executed if `conditionToTest` is truthy}else{// executed if `conditionToTest` is falsey}
- Define a function
teenager
that accepts an age as a parameter. If the age is between 13 and 19 it should return"You are a teenager!"
. Otherwise, the function should return"You are not a teenager"
.
if
statements can also be combined with anelse if
clause. This is like anelse
statement, but with its own condition. It will only run if its condition is true, and the previous statement's condition was false.
if(conditionToTest1){// condition is false hence code is not executed}elseif(conditionToTest2){// execute this code if `conditionToTest1`statement is falsey AND `conditionToTest2` is truthy}
You can optionally add a finalelse
statement after all of yourelse if
statements. You can probably guess what will happen: ifall of the other statements are falsey, this finalelse
block will execute; otherwise, an earlier statement executes and theelse
block is skipped.
if(conditionToTest1){// condition is false hence code is not executed}elseif(conditionToTest2){// execute this code if `conditionToTest1` statement is falsey AND `conditionToTest2` is truthy}else{// execute this code iff none of the other conditions are met}
- Define a function
ageChecker
that takes in an age as a parameter. If the age is between 13-19 it should return"You are a teenager!"
. If the age is 12 or below, it should return"You are a kid"
. If the age is above 19, it should return"You are a grownup"
Top tip: Remember, if you place areturn
statement before the end of the function, anything afterreturn
won't get executed. We can use this to make code terser:
functioncanGo(lightColor){if(lightColor==='green'){returntrue}returnfalse}
The above function will returntrue
iflightColor
is'green'
— go aheadand try it out.
canGo('green')// true
Andfalse
otherwise:
canGo('red')// false
Notice that we didn't have to use anelse
statement; we can just depend onreturn
.
We need to be careful withreturn
, however, because it's easy to return tooearly and not execute important parts of the function. For example,
functioncanGo(lightColor){returntrueif(lightColor==='red'){returnfalse}}
willalways returntrue
, even iflightColor
is'red'
. Try it!
canGo('red')// true
And that's a great way to cause an accident.
You can think of it as a shortcut for theif-else
statement.
This operator tests a condition; if the condition is truthy, it evaluates the left-hand side of the colon; otherwise it evaluates the right-hand side of the colon.
Syntax:
conditionToTest ?valueToBeReturnedIfTrue :valueToBeReturnedIfFalse
- Define a function
ternaryTeenager
that accepts age as a parameter. The body of the function should use the ternary operator to return"You are a teenager"
if age is between 13-19 and returns"You are not a teenager"
if the age is anything else.
Top tip: In order for the function to actuallyreturn the evaluation of the ternary operator, you'll need to prependreturn
to the expression:
returnconditionToTest ?valueToBeReturnedIfTrue :valueToBeReturnedIfFalse
Switch statements acts like a big if/else if/else chain. The switch expression is evaluated once and the value of the expression is compared with the values of each case. If there is a match, the associated block of code is executed.
Syntax:
switch(expression){casen:// code to be executed if case n is truebreak;// break out of switch statement once code executedcasem:// code to be executed if case m is truebreak;// break out of switch statement once code executeddefault:// all other cases// code to be executed if case n and case m false}
Example:
varmood="hungry"switch(mood){case"happy":console.log("Dance to Pharrell's 'Happy'");break;case"sad":console.log("You should eat a pint of ice cream");break;case"anxious":console.log("Take some deep breaths");break;case"hungry":console.log("You should eat a big chocolate cake");break;default:console.log("That's not a mood we support");}
In the example above, we'll see"You should eat a big chocolate cake"
printed to the console. If we change the value of themood
variable tosad
you'll see"You should eat a pint of ice cream"
. If the value ofmood
changed to"grumpy"
, the default statement would trigger and print out"That's not a mood we support"
.
- Define a function
switchAge
that accepts an age as a parameter. The case statement should switch onage
and return"You are a teenager"
if the age is 13, 14, 15, 16, 17, 18, or 19, and return"You have an age"
as the default.
As with any function,return
will halt execution at any point. Thus if wewrote,
functionfeelings(mood){switch(mood){case"happy":return"Dance to Pharrell's 'Happy'"default:return"I don't recognize that mood."}console.log("Let us know how you're feeling tomorrow!")}
theconsole.log()
statement at the bottom of the function willnever run. This is a major difference betweenreturn
andbreak
:return
exits the function andreturns a value;break
exits ablock and does not (generally speaking) have a value associated with it.
- Codecademy - if/if else/if else if else
- MDN - if..else
- Codecademy - Ternary Operator
- Codecademy - Switch Statements
ViewJavaScript Flow Control on Learn.co and start learning to code for free.
About
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Languages
- JavaScript88.7%
- Shell11.3%