Learn JavaScript Journey Part 3
|Learning JavaScript for the third day in a row. Learning a lot. Little by little.
And for this day things will escalate and we will start learning something more advanced. Lets hope. This part got stuck for various reasons, but we are resuming the work now.
In this part we will learn:
- Control Flow
- if/else Statements
- True and False Values
- Comparison Operators
- switch
- Ternary Operator
Control Flow
Control flow statements enable JavaScript programs to make decisions by executing code based on a condition. If a given condition is true, we execute one block of code. If the statement is false, we execute another block of code.
Basically it is a simple if / else statements letting you control the actions of your code. Logical statements. All conditions are evaluated to be truthy or falsy.
let userName = 'Tarantulo'; let knowsJavaScript = false; if (knowsJavaScript && userName) { console.log('Great, ' + userName + '! Get ready to practice your JavaScript!'); } else if (knowsJavaScript) { console.log('Great! Get ready to practice your JavaScript!'); } else if (userName) { console.log('Great, ' + userName + '! Get ready to learn something new!'); } else { console.log('Great! Get ready to learn something new!'); }
Output:
Great, Tarantulo! Get ready to learn something new!
if/else Statements
“If something is true, let’s do option 1, or else, if it is false, let’s do option 2.” This sentence looks fairly similar when we write it with JavaScript. if
/else
statements are how programs can process yes/no questions programmatically.
if
/else
statements make binary decisions and execute different code based on conditions.
let needsCoffee = true; if (needsCoffee === true) {console.log('Finding coffee'); } else { console.log('Keep on going!') } let isSoccerFan = true; if (isSoccerFan = true) {console.log('Goal!')} else { console.log('No goal!'); }
Output:
Finding coffee Goal!
True and False Values
In JavaScript, all variables and conditions have a truthy or falsy value. So basically if the value is true then it is as 1 and if it is false then it is falsy code acts as if it is 0.
let variableOne = 'I Exist!'; if (variableOne) { // This code will run because variableOne contains a truthy value. } else { // This code will not run because the first block ran. }
All variables that have been created and set are truthy (and will evaluate to true if they are the condition of a control flow statement) unless they contain one of the seven values listed below:
false
0
and-0
""
and''
(empty strings)null
undefined
NaN
(Not a Number)document.all
(something you will rarely encounter)
For example:
let wordCount = 1; if (wordCount) { console.log("Great! You've started your work!"); } else { console.log('Better get to work!'); } let favoritePhrase = 'Work'; if (favoritePhrase) { console.log("This string doesn't seem to be empty."); } else { console.log('This string is definitely empty.'); }
Output:
Great! You've started your work! This string doesn't seem to be empty.
True and False Values II
In programming, we often evaluate whether or not an expression is true or truthy. Conveniently, JavaScript provides a shorthand notation for this.
let isRaining = true; if (isRaining) { console.log('Carry an umbrella!'); } else { console.log('Enjoy the sun!'); }
In the example above, the condition is simply if (isRaining)
. In JavaScript, this is evaluating whether isRaining
is truthy. If you read the code out loud to yourself, it sounds like a simple sentence: “If it’s raining, carry an umbrella. Else, enjoy the sun!”
JavaScript provides an operator for swapping the truthiness and falsiness of values – the exclamation point (!
). We can use this in conditional statements as shorthand to check if the value of a variable evaluates to false rather than true.
let isPhoneCharged = true; if (!isPhoneCharged) { console.log('Plug in your phone!'); } else { console.log('No need to charge!'); }
In the example above, the program checks if isPhoneCharged
evaluates to false
. Because isPhoneCharged
is true
, the second block of code will execute.
Example:
let wordCount = 1; if (wordCount) { console.log("Great! You've started your work!"); } else { console.log('Better get to work!'); } let favoritePhrase = 'Work'; if (!favoritePhrase) { console.log("This string doesn't seem to be empty."); } else { console.log('This string is definitely empty.'); }
Output:
Great! You've started your work! This string is definitely empty.
Comparison Operators
In addition to checking whether a variable evaluates to true
or false
, sometimes we need to compare variables to other values. We can achieve this with comparison operators.
There are two comparisons you might be familiar with:
- Less than:
<
- Greater than:
>
You may also recognize these:
- Less than or equal to:
<=
- Greater than or equal to:
>=
These comparisons evaluate to true
or false
.
let hungerLevel = 5; if (hungerLevel > 7) { console.log ('Time to eat!'); } else { console.log('We can eat later!'); }
Output:
We can eat later!
Comparison Operators II
There are two more useful comparisons we can make. Often, we might want to check if two things are equal to each other or if they are not.
- To check if two things equal each other, we write
===
(three=
signs in a row). - To check if two things do not equal each other, we write
!==
(an exclamation with two=
signs in a row).
It can be confusing when to use one =
sign and when to use three ===
signs. Use a single =
to assign a value to a variable. Use ===
to compare the values of two different variables.
Also there is an option to use two ==
equal signs. The differece is this:
The identity (===
) operator behaves identically to the equality (==
) operator except no type conversion is done, and the types must be the same to be considered equal. The ===
operator will not do the conversion, so if two values are not the same type ===
will simply return false
. Both are equally quick.
var moonPhase = "full"; if (moonPhase !== "full"){ console.log("Howl!") } else { console.log("I swear I am not a werewolf.") }
Output:
I swear I am not a werewolf.
else if Statements
Multiple statements are also possible. We can add more conditions to our if
/else
statement with else if
.
In the example code below we can learn the syntax of multiple else if statements.
let moonPhase = "solar eclipse"; if (moonPhase === "full"){ console.log("Howl!") } else if (moonPhase === "mostly full") { console.log("Arms and legs are getting hairier") } else if (moonPhase === "mostly new") { console.log("Back on two fee") } else { console.log("Invalid moon phase") }
Output:
Invalid moon phase
Logical Operators
In English, sometimes we say “both of these things” or “either one of these things.” Let’s translate those phrases into JavaScript with special operators called logical operators.
- To say “both must be true,” we use
&&
. - To say “either can be true,” we use
||
.
In this example we use || to test the code:
let moonPhase = "full"; let isFoggyNight = false; if (moonPhase === "full" || isFoggyNight === true){ console.log("Howl!") } else if (moonPhase === "mostly full") { console.log("Arms and legs are getting hairier") } else if (moonPhase === "mostly new") { console.log("Back on two fee") } else { console.log("Invalid moon phase") }
switch Statements
Writing complex statements that will require a lot if/else statements and sometimes things get very complex. To deal with times when you need many else if
conditions, we can turn to a switch
statement to write more concise and readable code.
To a computer, a switch
statement and an if
/else
statement are the same, but a switch
statement can be easier for other humans to read. Part of being a good developer is writing code that both computers and other humans can read.
switch
statements look like this:
let groceryItem = 'papaya'; switch (groceryItem) { case 'tomato': console.log('Tomatoes are $0.49'); break; case 'lime': console.log('Limes are $1.49'); break; case 'papaya': console.log('Papayas are $1.29'); break; default: console.log('Invalid item'); break; }
- The
switch
keyword initiates the statement and is followed by( ... )
, which contains the condition that eachcase
will compare to. - Inside the block,
{ ... }
, there arecase
s.case
is like theelse if
part of anif
/else if
/else
statement. - Then the program stops with the
break
keyword. This keyword will prevent theswitch
statement from executing any more of its code. Without addingbreak
at the end of each case, the program will execute the code for all matching cases and the default code as well. This behavior is different fromif
/else
conditional statements which execute only one block of code. - At the end of each
switch
statement, there is adefault
condition. If none of thecase
s are true, then this code will run.
Another example of the same code with switch:
let moonPhase = "full"; switch (moonPhase) { case 'full': console.log("Howl!"); break; case 'mostly full': console.log("Arms and legs are getting hairier"); break; case 'mostly new': console.log("Back on two fee"); break; default: console.log("Invalid moon phase"); break; }
Ternary Operator
Ternary operators provide a way to shorten and simplify if
/else if
/else
statements to make them easier to read. And it is really short and fast to write.
let isNightTime = true; if (isNightTime) { console.log('Turn on the lights!'); } else { console.log('Turn off the lights!'); }
In the example above, we see a very familiar pattern. See the example below for an equivalent way to express this.
isNightTime ? console.log('Turn on the lights!') : console.log('Turn off the lights!');
The code in the example above will operate exactly as the code from the previous example. Let’s break this example into its parts:
isNightTime ?
— the conditional statement followed by a question mark. This checks ifisNightTime
is truthy.console.log ('Turn on the lights!')
— this code will be executed if the condition is truthy.:
— a colon separates the two different blocks of code that can be executed.console.log('Turn off the lights!');
— this code will be executed if the condition is falsy
age >= 16 ? console.log('You are old enough to drive in the United States!') : console.log('You are not old enough to drive in the United States!');
A few more example with ternary operators:
let isLocked = false; isLocked ? console.log('You will need a key to open the door.') : console.log('You will not need a key to open the door.'); let isCorrect = true; isCorrect ? console.log('Correct!') : console.log('Incorrect!') let favoritePhrase = 'Love That!'; favoritePhrase === 'Love That!' ? console.log('I love that!') : console.log("I don't love that!");
Output:
You will not need a key to open the door. Correct! I love that!
Go to the third 4 part >>