How to fix NaN error in JavaScript?

To fix a NaN error in JavaScript, don't mix numbers with non-numbers in arithmetics, and make sure, that the string that you pass into parseInt and parseFloat holds a number.

Don't mix numbers with non-numbers in arithmetics

Check whether you're adding, subtracting, multiplying or dividing a number by something other than a number (like a string or an object):

const ok = 3 / 2;
const nan1 = 3 / 'a';
const nan2 = 3 / {};

console.log(ok); // 1.5
console.log(nan1); // NaN
console.log(nan2); // NaN

parseInt and parseFloat

Check whether you're trying to parse something, that cannot be turned into a number:

const ok1 = parseInt('345');
const ok2 = parseFloat('345.67');
const nan1 = parseInt('Hello World!');
const nan2 = parseFloat(true);
const nan3 = parseFloat([ 'Hello', 'World' ]);

console.log(ok); // 345
console.log(ok2); // 345.67
console.log(nan1); // NaN
console.log(nan2); // NaN
console.log(nan3); // NaN