Looking at a javascript expression:
return product.id === +id;
I've never seen a +
sign in front of a variable like this before...Thoughts?
Looking at a javascript expression:
return product.id === +id;
I've never seen a +
sign in front of a variable like this before...Thoughts?
It converts a variable to a Number, if success: +id equals Number(id). If the conversion fails, it will return NaN
The plus sign in front of your variable is called a Unary Operator and it's used to convert a variable into a number. If the value is numeric, the result of the operation will be a number, otherwise NaN
.
You can roughly equate the +
operator's functionality to parseFloat
. However, note that the former can only parse a numeric string, while the latter can extract the numeric value even if it's followed by another one that's not.
Example:
var a = "0x";
console.log("Unary Operator:", +a);
console.log("parseFloat:", parseFloat(a, 16));
In your particular case, it's used to make sure that, if turned into a number, the id
is strictly equal to product.id
. If id
isn't numeric the function will return false
, because product.id != NaN
, even if product.id
itself equals NaN
.
Example:
var
id1 = 13,
id2 = "13",
id3 = "a13";
console.log("number:", id1);
console.log("numeric string:", +id2);
console.log("non-numeric string:", +id3);
console.log("NaN !== NaN:", +id3 !== +id3);
Just a Note:
Despite NaN
literally meaning "Not a Number"
, if you use typeof NaN
the result will be "number"
, even though NaN
isn't a number in the mathematical sense of the word.
Relevant Threads: