this post was submitted on 17 May 2025
502 points (97.9% liked)

Programmer Humor

23848 readers
2535 users here now

Welcome to Programmer Humor!

This is a place where you can post jokes, memes, humor, etc. related to programming!

For sharing awful code theres also Programming Horror.

Rules

founded 2 years ago
MODERATORS
 
you are viewing a single comment's thread
view the rest of the comments
[–] [email protected] 4 points 2 weeks ago (2 children)

probably not true in most other langauges. although I'm not well versed in the way numbers are represented in code and what makes a number "NaN", something tells me the technical implications of that would be quite bad in a production environment.

the definitive way to check for NaN in JS would probably be something like

// with `num` being an unknown value

// Convert value to a number
const res = Number(num);

/*
 * First check if the number is 0, since 0 is a falsy
 * value in JS, and if it isn't, `NaN` is the only other
 * falsy number value
 */
const isNaN = res !== 0 && !res;
[–] [email protected] 2 points 1 week ago* (last edited 1 week ago)

Another way to check whether a number is NaN:

const isNaN = res !== res;

As NaN is the only value out there that is not equal to itself. See my other comment on this post for more: https://programming.dev/comment/17221245

This comparison should work in every programming language out there that implements/respects/uses IEEE 754 floating point numbers.

[–] [email protected] 2 points 2 weeks ago

NaN is a special floating point value. https://en.wikipedia.org/wiki/IEEE_754

It's weird but it makes sense why it was chosen to be this way.