Back

Technologies:

javascriptjavascript
avatar
Tolerim
a month ago

How can I remove NaNs from an array while keeping other records intact?

As a senior JavaScript developer, I have been experimenting with the code in Firefox's JavaScript console. Despite my attempts, neither of the given statements display true when executed: parseFloat('geoff') == NaN;

parseFloat('geoff') == Number.NaN;

However, the code is correct, and I can confirm that both statements are utilizing the correct syntax.
Answers(2)
avatar
Vogi
a month ago
Verified Answer
The reason why both statements are not true is that NaN is not equal to any value, including itself. Therefore, parseFloat('geoff') == NaN; and parseFloat('geoff') == Number.NaN; will both return false. Instead, you can use the global function isNaN() to check if a value is NaN or not. For example:
The parseFloat() function converts its first argument to a string, parses that string as a decimal number literal, then returns a number or NaN. The number syntax it accepts can be summarized as: The characters accepted by parseFloat() are plus sign (+), minus sign (-U+002D HYPHEN-MINUS), decimal digits (0 – 9), decimal point (.). However, parseFloat() is more lenient than Number() because it ignores trailing invalid characters, which would cause Number() to return NaN. I hope this helps! Let me know if you have any other questions.

Sources

parseFloat() - JavaScript | MDN - Mozilla DeveloperWhy does Number(null) return 0, and parseFloat(null) return NaN?How do you check that a number is NaN in JavaScript?parseFloat() - JavaScript | MDN
avatar
Tolerim
a month ago
The reason why neither of the following statements return true is because in JavaScript, you cannot use the equality operator (==) to test whether a value is NaN. Instead, you should use the isNaN() function to test whether a value is NaN. Here's an example of how to use isNaN():
isNaN(parseFloat('geoff')); // returns true
In this example, we use the parseFloat() function to attempt to parse the string 'geoff' as a float. Since 'geoff' is not a valid number, parseFloat() returns NaN. We then pass the result of parseFloat() to the isNaN() function, which returns true because the value is NaN. Note that Number.NaN is the same as NaN, and that both are used to represent the "Not a Number" value in JavaScript.
;