본문으로 건너뛰기

switch-case, truthy/falsy

switch-case, truthy/falsy

In this lesson, we'll delve into advanced concepts of conditional statements.


switch-case Statement

A switch-case statement is used to compare a specific value against several other values. It's especially suited for menus or multiple-choice structures.

switch (expression) {
case value1:
// Code to be executed when it matches value1
break;
case value2:
// Code to be executed when it matches value2
break;
// ... (there can be more cases)
default:
// Code to be executed when no case matches
}

break and default

break exits the switch-case statement once the condition is met, preventing further conditions from being checked. If break is omitted, the execution continues with the subsequent conditions even if a match is found.

default is where you write the code that will be executed if the given expression doesn't match any cases.


Example

let fruit = 'apple';
switch (fruit) {
case 'banana':
console.log('It is a banana.');
break;
case 'apple':
console.log('It is an apple.');
break;
default:
console.log('Unknown fruit.');
}
// Output: It is an apple.

Using Ternary Operators for Conditional Statements

Ternary operators allow you to express a simple if-else structure more concisely.

condition ? value if true : value if false

Concise Condition Evaluation

Ternary operators make the code more concise for simple conditional evaluations.


Example

let age = 19;
let result = age >= 20 ? 'adult' : 'teenager';
console.log(result); // Output: teenager

truthy and falsy

  • True and False in JavaScript

In JavaScript, true and false are not the only values that represent truth and falsehood.

Generally, if a value converts to true in a boolean context, it is truthy; if it converts to false, it is falsy.


  • Examples of truthy and falsy Values

Here are examples of falsy values:

  • false
  • 0
  • "" (empty string)
  • null
  • undefined
  • NaN

All other values are truthy.


Logical Short-Circuiting

  • Using && and || Operators for Conditional Statements

The && operator evaluates the right-hand side only if the left-hand side is truthy, and the || operator evaluates the right-hand side only if the left-hand side is falsy. This characteristic allows for simpler conditional statements.

  • Example
let name = null;
let displayName = name || 'user';
console.log(displayName); // Output: user

다음 내용이 궁금하다면?

월 12,500원 PLUS 멤버십 가입 or 강의를 등록해 주세요!