Cannot read property 'replace' of null when turning a string value into Number

Viewed 544

Hey im trying to convert a string that holds numbers but the string has commas in it and I'm trying to remove those commas as well.

let why = "42,343,324"
console.log(typeof why) // string
let noCommas = parseFloat(why.replace(/,/g, ''));
console.log(noCommas) // 42343324

but when I replace why value with a prop value, it gives me an error saying Cannot read property 'replace' of null

let why = visitsPerPerson
console.log(typeof why)
let noCommas = parseFloat(why.replace(/,/g, ''));
console.log(noCommas)

Output: Cannot read property 'replace' of null

The prop is a string value that holds numbers returned from an API the prop itself doesn't return null but returns a string with numbers in it and can verify when I console log: console.log(visitsPerPerson)

1 Answers

I re-produced the second code snippet and got expected output:

NaN (Not a Number), which is correct and the expected result for "visitsPerPerson".

Did I understand something wrong?

let why = "visitsPerPerson";
console.log(typeof why); // string
let noCommas = parseFloat(why.replace(/,/g, ''));
console.log(noCommas); // NaN (Not a Number, which is correct)

Related