Johnny Chen
Johnny Chen

Reputation: 2070

Javascript type coercion using parseFloat().toFixed()?

Can Someone explain this thoroughly,why the third expression returns NaN?

NaN || 0 // 0 
parseFloat("s").toFixed() // NaN 
parseFloat("s").toFixed() || 0 // NaN

Upvotes: 1

Views: 182

Answers (2)

Jaromanda X
Jaromanda X

Reputation: 1

Line 1: NaN is falsey, therefore NaN || 0 becomes 0

the method .toFixed results in a string, so

Line 2: parseFloat("s") -> NaN (this is the value NaN), then NaN.toFixed() -> "NaN" ... hence the result is the STRING "NaN" (not the value NaN)

Line 3: same as Line2, then, as a non-empty string is "truthy", "NaN" || 0 -> "NaN" (note, still a string)

P.S. I don't think there's any type coercion going on here (I may be wrong though)

Upvotes: 5

Tushar Gupta
Tushar Gupta

Reputation: 15923

This is because you get "NAN" || 0 not NAN || 0 as parseFloat("s").toFixed will return "NAN" not NAN

Upvotes: 1

Related Questions