I have this line that I copied from another place:
Total += parseFloat($(this).val())|0;
What’s the function of the operator |? When I change the number, I get different results.
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.
The
|in JavaScript is an integer bitwise OR operator. In that context, it strips off any fractional portion returned byparseFloat. The expressionparseFloat($(this).val())will result in a number with (potentially) a fractional component, but then|0will convert it to an integer number, OR it with0(which means it won’t change), and so the overall result is to get a whole number.So functionally, it truncates the fractional portion off the number.
-1.5becomes-1, and1.5becomes1. This is likeMath.floor, but truncating rather than rounding “down” (Math.floor(-1.5)is-2— the next lowest whole number — rather than-1as the|0version gives us).So perhaps that’s why it was used, to chop off (rather than “floor”) the fractional portion of the number.
Alternately, it could be a typo. The author of that code might have meant to write this (note
||rather than|):That defends against the possibility that
$(this).val()returns""or similar, resulting inparseFloatreturningNaN. It uses the curiously-powerful||operator to return0rather thanNaNin that case. (And there’s an advertisement for putting spaces around your operators.) Would have to know the context of the code to say whether truncating to a whole number (|) makes sense when adding toTotal, or if they were just defending theNaNcase.