Conditional Statement + Truthy/Falsy + logical/comparison + short circuit evaluation + Ternary operator + Switch statement

Yoseob Shin·2022년 3월 26일
0

javascript

목록 보기
6/24
post-custom-banner

Conditional statement:

Conditionals take an expression, which is code that evaluates to determine a value, and checks if it is true or false. If it’s true, we can tell our program to do one thing — we can even account for false to do another.

The following concepts:

  • if, else if, and else statements
  • comparison operators
  • logical operators
  • truthy vs falsy values
  • ternary operators
  • switch statement

If statement

In programming, we can also perform a task based on a condition using an if statement:

  • The if keyword followed by a set of parentheses () which is followed by a code block, or block statement, indicated by a set of curly braces {}.
  • Inside the parentheses (), a condition is provided that evaluates to true or false.
  • If the condition evaluates to true, the code inside the curly braces {} runs, or executes.
if (true) {
  console.log('This message will print!'); 
}
// Prints: This message will print!

if...else statement

In many cases, we’ll have code we want to run if our condition evaluates to false.

If we wanted to add some default behavior to the if statement, we can add an else statement to run a block of code when the condition evaluates to false.

if (false) {
  console.log('The code in this block will not run.');
} else {
  console.log('But the code in this block will!');
}
 
// Prints: But the code in this block will!
  • An else statement must be paired with an if statement, and together they are referred to as an if...else statement.
  • Uses the else keyword following the code block of an if statement.
  • Has a code block that is wrapped by a set of curly braces {}.
  • The code inside the else statement code block will execute when the if statement’s condition evaluates to false.

Comparison operators

When writing conditional statements, sometimes we need to use different types of operators to compare values. These operators are called comparison operators.

Here is a list of some handy comparison operators and their syntax:

  • Less than: <
  • Greater than: >
  • Less than or equal to: <=
  • Greater than or equal to: >=
  • Is strict equal to: ===
  • Is strict not equal to: !==

It can be helpful to think of comparison statements as questions. When the answer is “yes”, the statement evaluates to true, and when the answer is “no”, the statement evaluates to false

We can also use comparison operators on different data types like strings:

'apples' === 'oranges' // false
In the example above, we’re using the identity or strict operator (===) to check if the string 'apples' is the same as the string 'oranges'. Since the two strings are not the same, the comparison statement evaluates to false.

Strict equality compares two values for equality.

// If you try to test if the number 5 
//is equal to the string “5” the result is true. 
var a = 5; 
var b = "5"; 
if ( a == b) --> true
//That’s because JavaScript figures out the value 
//of this string is five, and five is the same as five, 
//so therefore a equals b.

//But if you ever need to test to see 
//if two things are identical, three symbols is the way to go. 
var a = 5; 
var b = "5"; 
if ( a === b) --> false

Logical Operators

Working with conditionals means that we will be using booleans, true or false values. In JavaScript, there are operators that work with boolean values known as logical operators.

  • the and operator (&&) (multiple conditions must be evaluated to true)
  • the or operator (||) (only either one condition needs to be evaluated to true)
  • the not operator, otherwise known as the bang operator (!) (negate(무효화) boolean value)

Truthy and Falsy

consider how non-boolean data types, like strings or numbers, are evaluated when checked inside a condition.

Sometimes, you’ll want to check if a variable exists and you won’t necessarily want it to equal a specific value — you’ll only check to see if the variable has been assigned a value.

let myVariable = 'I Exist!';
 
if (myVariable) {
   console.log(myVariable)
} else {
   console.log('The variable does not exist.')
}

List of Falsy:

  • 0
  • Empty strings like "" or ''
  • null which represent when there is no value at all
  • undefined which represent when a declared variable lacks a value
  • NaN, or Not a Number
    * img from MDN

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 username = '';
let defaultName;
 
if (username) {
  defaultName = username;
} else {
  defaultName = 'Stranger';
}
 
console.log(defaultName); // Prints: 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:

let username = '';
let defaultName = username || 'Stranger';
 
console.log(defaultName); // Prints: Stranger

short-circuit evaluation

Because || or statements check the left-hand condition first, the variable defaultName will be assigned the actual value of username if it is truthy, and it will be assigned the value of 'Stranger' if username is falsy.


Ternary Operator

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:

isNightTime ? console.log('Turn on the lights!') : console.log('Turn off the lights!');

Tip: Ternary conditions can be chained.
example below But not encouraged because of code readability.

function example(…) {
    return condition1 ? value1
         : condition2 ? value2
         : condition3 ? value3
         : value4;
}

if...else and else if

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!');
}

The else if statements allow you to have multiple possible outcomes. if/else if/else statements are read from top to bottom, so the first condition that evaluates to true from the top to bottom is the block that gets executed.


Switch keyword

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;
}
 
// Prints 'Papayas are $1.29'

Note: Without break keywords, the first matching case will run, but so will every subsequent case regardless of whether or not it matches—including the default. This behavior is different from if/else conditional statements that execute only one block of code.


Review

  • 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 cases from being checked and executed in a switch statement.

Ref:

https://www.digitalocean.com/community/posts/5-tips-to-write-better-conditionals-in-javascript

profile
coder for web development + noodler at programming synthesizers for sound design as hobbyist.
post-custom-banner

0개의 댓글