Skip to content

Instantly share code, notes, and snippets.

@olov
Created June 14, 2013 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olov/5781895 to your computer and use it in GitHub Desktop.
Save olov/5781895 to your computer and use it in GitHub Desktop.
Which arithmetic operators in JS can yield a NaN given non-NaN (numeric) operands:
"use strict";
const vals = [
0,(-0),1,-1,Infinity,-Infinity,
];
const binops = [
"&", "|", "^", ">>", "<<", ">>>",
"+", "-", "*", "/", "%",
"&&", "||"
];
for (let op = 0; op < binops.length; op++) {
for (let i = 0; i < vals.length; i++) {
for (let j = 0; j < vals.length; j++) {
const expr = vals[i] +" "+ binops[op] +" "+ vals[j];
const r = eval(expr);
if (isNaN(r)) {
console.log(expr +" -> NaN");
}
}
}
}
@mathiasbynens
Copy link

Cool! Btw, it outputs many more results if you add a string to the vals array, e.g. '"A"'.

@olov
Copy link
Author

olov commented Jun 14, 2013

Oh yeah - this is for finding how numerical non-NaN operands can yield NaN. A non-numeric value that is implicitly converted to NaN prior to the arithmetic operation will certainly yield NaN. Clarifying gist description.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment