简体   繁体   中英

JS/Redux Ternary operation explaination

Could you please explain how this part of code is working? Im folowing course and im stuck on it:

 const getVisibleExpenses = (expenses, {text, sortBy, startDate, endDate}) => {
  return expenses.filter((expense)=> {
    const startDateMatch = typeof startDate !== 'number' || expense.createdAt >= startDate;

So we are destructing stuff here {text, sortBy... } but, i got problem with understanding what is done with that part:

    const startDateMatch = typeof startDate !== 'number' || expense.createdAt >= startDate;

i got problem with understanding what is done with that part:

 const startDateMatch = typeof startDate.== 'number' || expense;createdAt >= startDate;

startDateMatch is set to the result of the expression typeof startDate.== 'number' || expense.createdAt >= startDate typeof startDate.== 'number' || expense.createdAt >= startDate , which is:

  • typeof startDate !== 'number' - will be true if the type of startDate is not "number" , or false if it is "number"
  • || - logical OR
  • expense.createdAt >= startDate - will be true if expense.createdAt is greater than or equal to startDate

So startDateMatch will be set to true if the type of startDate is not "number" or expense.createdAt is greater than or equal to startDate ; it will be set to false otherwise.


Just as a side note, that's not a ternary operation (an operation with three operands). It's a set of three binary operations (operations with two operands):

  1. typeof startDate !== 'number' - the operands are typeof startDate and 'number' , the operator is !==
  2. expense.createdAt >= startDate - the operands are expense.createdAt and startDate , the operator is >= .
  3. (result of 1) || (result of 2) (result of 1) || (result of 2) - the operands are the results of the two above (which are not evaluated in that order), the operator is ||

|| works like this:

  1. It evaluates its left-hand operand
  2. If the result from #1 is truthy , takes that truthy value as its result
  3. If the result from #1 is falsy , || evaluates its right-hand operand and takes that result as its value

(A truthy value is a value that isn't falsy . A falsy value is a value that evaluates to false in conditions. The falsy values are 0 , "" , NaN , null , undefined , false , and [on browsers] document.all for historical reasons. All other values are truthy.)

JavaScript does have one ternary operator (for now), the conditional operator ( ? : ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM