Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

246
Views
Shorthand way to write Conditional in Javascript

I usually run into writing conditionals like this and I'm wondering if there a short hand way to write something similar below without calling a function

const currentValue = this.props.book.location.areaValueInDollars ? this.props.book.location.areaValueInDollars : 0; 
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Use nullish coalescing operator:

this.props.book.location.areaValueInDollars || 0

More on the subject here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

about 4 years ago · Juan Pablo Isaza Report

0

You can use short-circuiting and the Logical OR operator.

const currentValue = window['a'] || 0; 

console.log(currentValue);

If the variable exists, then the first operand will return true, causing it to "short circuit" and be returned. The second operand is only evaluated if the first is false, since the expression is evaluated from left to right.


Using the Logical OR operator has a caveat though. If the variable is 0, null, undefined... (for full list, see Falsy values), it will return false.

To solve this, we can use the Nullish coalescing operator, which will only return the right-hand side operand if the left operand is null or undefined. Like so:

const currentValue = window['a'] ?? 0; 

console.log(currentValue);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!