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

Top comments (0)