DEV Community

Rickvian Aldi
Rickvian Aldi

Posted on

parseInt vs _.toInteger vs _.toNumber

const _ = require('lodash')

const values = [
  null,
  undefined,
  '11text',
  'null',
  'NaN',
  'Infinity',
  '',
  '19.5',
]

values.forEach((value) => {
  console.log(`_.toInteger(${JSON.stringify(value)}):`, _.toInteger(value))
  console.log(`_.toNumber(${JSON.stringify(value)}):`, _.toNumber(value))
  console.log(`parseInt(${JSON.stringify(value)}):`, parseInt(value))
  console.log(`\n`)
})

Enter fullscreen mode Exit fullscreen mode

Results:

_.toInteger(null): 0
_.toNumber(null): 0
parseInt(null): NaN


_.toInteger(undefined): 0
_.toNumber(undefined): NaN
parseInt(undefined): NaN


_.toInteger("11text"): 0
_.toNumber("11text"): NaN
parseInt("11text"): 11


_.toInteger("null"): 0
_.toNumber("null"): NaN
parseInt("null"): NaN


_.toInteger("NaN"): 0
_.toNumber("NaN"): NaN
parseInt("NaN"): NaN


_.toInteger("Infinity"): 1.7976931348623157e+308
_.toNumber("Infinity"): Infinity
parseInt("Infinity"): NaN


_.toInteger(""): 0
_.toNumber(""): 0
parseInt(""): NaN


_.toInteger("19.5"): 19
_.toNumber("19.5"): 19.5
parseInt("19.5"): 19

Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay