5day javaScript
Truthy and Falsy Assignment
Truthy and falsy evaluations open a world of short-hand possibilities!
Say you have a website and want to take a user’s username to make a personalized greeting. Sometimes, the user does not have an account, making the
username
variable falsy. The code below checks if username
is defined and assigns a default string if it is not:
let defaultName;
if (username) {
defaultName = username;
} else {
defaultName = 'Stranger';
}
If you combine your knowledge of logical operators you can use a short-hand for the code above. In a boolean condition, JavaScript assigns the truthy value to a variable if you use the
||
operator in your assignment:
If you combine your knowledge of logical operators you can use a short-hand for the code above. In a boolean condition, JavaScript assigns the truthy value to a variable if you use the
||
operator in your assignment:
let defaultName = username || 'Stranger';
ecause ||
or statements check the left-hand condition first, the variable defaultName
will be assigned the actual value of username
if is truthy, and it will be assigned the value of 'Stranger'
if username
is falsy. This concept is also referred to as short-circuit evaluation.
.
Let’s use short-circuit evaluation to assign a value to writingUtensil
. Do not edit tool
yet, we’ll return to tool
in the next step.
Assign to writingUtensil
the value of tool
and if tool
is falsy, assign a default value of 'pen'
.
Notice that text 'The pen is mightier than the sword'
logged to the console. Which means the value of writingUtensil
is 'pen'
.
What if we reassign the value of tool
to 'marker'
. Let’s see what happens to the value of writingUtensil
.
let tool = '';
tool = 'marker';
// Use short circuit evaluation to assign writingUtensil variable below:
let writingUtensil = tool || 'pen';
console.log(`The ${writingUtensil} is mightier than the sword.`);
Ternary Operator
In the spirit of using short-hand syntax, we can use a ternary operator to simplify an if...else
statement
Take a look at the if...else
statement example:
We can use a ternary operator to perform the same functionality:
let isNightTime = true;
if (isNightTime) {
console.log('Turn on the lights!');
} else {
console.log('Turn off the lights!');
}
We can use a ternary operator to perform the same functionality:
let isNightTime = true;
isNightTime ? console.log('Turn on the lights!') : console.log('Turn off the lights!');
- The condition,
isNightTime
, is provided before the ?
.
- Two expressions follow the
?
and are separated by a colon :
.
- If the condition evaluates to
true
, the first expression executes.
- If the condition evaluates to
false
, the second expression executes.
Like if...else
statements, ternary operators can be used for conditions which evaluate to true
or false
.
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!");
Else If Statements
We can add more conditions to our if...else
with an else if
statement. The else if
statement allows for more than two possible outcomes. You can add as many else if
statements as you’d like, to make more complex conditionals!
he else if
statement always comes after the if
statement and before the else
statement. The else if
statement also takes a condition. Let’s take a look at the syntax:
The else if
statement always comes after the if
statement and before the else
statement. The else if
statement also takes a condition. Let’s take a look at the syntax:
let stopLight = 'yellow';
if (stopLight === 'red') {
console.log('Stop!');
} else if (stopLight === 'yellow') {
console.log('Slow down.');
} else if (stopLight === 'green') {
console.log('Go!');
} else {
console.log('Caution, unknown!');
}
'It\'s sunny and warm because it\'s summer!'
else if
statements are a great tool if we need to check multiple conditions
A switch
statement provides an alternative syntax that is easier to read and write. A switch
statement looks 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;
}
A switch
statement provides an alternative syntax that is easier to read and write. A switch
statement looks 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 value that each case
will compare. In the example, the value or expression of the switch
statement is groceryItem
.
- Inside the block,
{ ... }
, there are multiple case
s. The case
keyword checks if the expression matches the specified value that comes after it. The value following the first case
is 'tomato'
. If the value of groceryItem
equalled 'tomato'
, that case
‘s console.log()
would run.
- The value of
groceryItem
is 'papaya'
, so the third case
runs— Papayas are $1.29
is logged to the console.
- The
break
keyword tells the computer to exit the block and not execute any more code or check any other cases inside the code block. Note: Without the break
keyword at the end of each case, the program would execute the code for all matching cases and the default code as well. This behavior is different from if
/else
conditional statements which execute only one block of code.
- At the end of each
switch
statement, there is a default
statement. If none of the case
s are true, then the code in the default
statement will run.
CONDITIONAL STATEMENTS
Review
Way to go! Here are some of the major concepts for conditionals:
- An
if
statement checks a condition and will execute a task if that condition evaluates to true
.
if...else
statements make binary decisions and execute different code blocks based on a provided condition.
- We can add more conditions using
else if
statements.
- Comparison operators, including
<
, >
, <=
, >=
, ===
, and !==
can compare two values.
- The logical and operator,
&&
, or “and”, checks if both provided expressions are truthy.
- The logical operator
||
, or “or”, checks if either provided expression is truthy.
- The bang operator,
!
, switches the truthiness and falsiness of a value.
- The ternary operator is shorthand to simplify concise
if...else
statements.
- A
switch
statement can be used to simplify the process of writing multiple else if
statements. The break
keyword stops the remaining case
s from being checked and executed in a switch
statement.
Comments
Post a Comment