-1

Trying to access the value of the page on the query I wrote this code:

const page = parseInt(req.query.page) ?? 1

But when I tried to use page it says that it's Nan. Changing the code in:

const page = parseInt(req.query.page) || 1

returns a normal integer instead. Why is this happening?

matteo
  • 115
  • 1
  • 7
  • 3
    `NaN` is false-y, but it's **not** `null` or `undefined`. See e.g. the opening paragraphs of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator, which explicitly compare `??` and `||`. – jonrsharpe Jun 04 '21 at 14:42

1 Answers1

0

|| will evaluate to the right-hand side if the left-hand side is falsey. The only numbers that can be falsey are 0 and NaN. If

parseInt(req.query.page)

evaluates to either of those, the whole expression will evaluate to the right side, the 1.

??, in contrast, evaluates to the right side if the left side is undefined or null. parseInt will never return undefined or null, so

const page = parseInt(req.query.page) ?? 1

is equivalent to

const page = parseInt(req.query.page)
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320