Blog Day 31: Conditional (ternary) Operator

Inseo Park·2021년 8월 7일
0

Path to Data Scientist

목록 보기
30/58
post-thumbnail

1. TIL (Today I Learned)

Conditional (ternary) Operator

Is used in React (JSX) to process 'if' statements in JS. I will have to study if 'if' statements does not work in JSX or is this new way just a alternative.

Syntax

condition ? expIfTrue : expIfFalse

Parameters

condition

An expression whose value is used as a condition.

expIfTrue

An expression which is evaluated if the condition evaluates to a truthy value(one which equals or can be converted to true)

expIfFalse

An expression which is executed if the condition is falsy (that is, has a value which can be converted to false).

Description

Besides false, possibly falsy expressions ave: null,NaN, O, the empty(" "), and undefined. If condition is any of these, the result of the conditional expression will be the result of executing the expression expIfFalse.

Examples

A simple example

var age = 26;
var beverage = (age >= 21) ? "Beer" : "Juice";
console.log(beverage); // "Beer"

Handling null values
One common usage is to handle a value that may be null:

let greeting = person => {
  let name = person ? person.name : 'stranger'
  return 'Howdy, ${name}`
}

console.log({name:'Alice'})); // 'Howdy, Alice'
console.log(greeting(null)); // 'Howdy, stranger'

Conditional chains
The ternary operator is right-associative, which means it can be "chained" in the following way, similar to an if... else if... else if... else chain:

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

// Equivalent to

function example(...) {
  if (condition1) {return value1;}
  else if (condition2) {return value2;}
  else if (condition3} {return value3;}
  else {return value4;}
}

2. 3 Things to be thankful for

  1. Thank God for allowing me to sleep well.
  2. Thank God for allowing me to have a good pair programming.
  3. Thank God for allowing me to have a good weekend.

3. Ideas and Things to Think about

  1. React is a powerful tool in programming.
  2. Finish a algorithm question a day to keep in pace.
profile
my journey to become a data scientist.

0개의 댓글