Multiplying someVariable
by 1
will cause implicit conversion to a number. This is the same as doing someVariable - 0
or +someVariable
or the explicit Number(someVariable)
.
One downside to using the proposed method is that using a unary plus (+
) or calling Number
as a version for the conversion is idiomatic in JavaScript, which means it's well understood, so using another method to achieve the same can be confusing and make your code harder to read.
However, there is another aspect - the result of all of those conversions would not accurately tell you if the value was a number or not. Consider the following:
function isNumber(someVariable) {
if(someVariable*1) {
console.log(`"${someVariable}" is a number. For real: ${typeof someVariable}`)
} else {
console.log(`"${someVariable}" is not a number. It was a ${typeof someVariable}`)
}
}
//these are correct
isNumber(1);
isNumber("abc");
//these are incorrect
isNumber(0);
isNumber("123");
isNumber(" 321");
isNumber([1]); //logged as simply *1* the string value of an array with with one element is that element
var obj = {
name: "Fred",
age: 42,
valueOf: function() {
return this.age;
}
}
//this is also incorrect
isNumber(obj)
Checking the result of some operation would, by definition, tell you about the result of that operation. So, checking if something can be implicitly converted to a number by examining the result would tell you exactly that - the source could be implicitly converted to a number.
Furthermore, when doing if (resultOfImplicitConversion)
you are checking if that result is truthy or falsy. That's not the same as checking it's type.
So, the pitfalls of your proposed method is that it is inaccurate in both steps of its attempted verification, and it also possibly inaccurately presents your intentions to future readers of your code (including yourself).
If you want to check if a value is a number, then follow this great answer on Stack Overflow