Is there a way to convert NaN values to 0 without an if statement? Example:
if (isNaN(a)) a = 0;
It is very annoying to check my variables every time.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can do this:
…which will convert a from any “falsey” value to
0.The “falsey” values are:
falsenullundefined0""( empty string )NaN( Not a Number )Or this if you prefer:
…which will have the same effect as above.
If the intent was to test for more than just
NaN, then you can do the same, but do a toNumber conversion first.This uses the unary + operator to try to convert
ato a number. This has the added benefit of converting things like numeric strings'123'to a number.The only unexpected thing may be if someone passes an Array that can successfully be converted to a number:
Here we have an Array that has a single member that is a numeric string. It will be successfully converted to a number.