What is the function of & ldquo; | & rdquo; (pipe) operator?

advertisements

This question already has an answer here:

  • Using bitwise OR 0 to floor a number 5 answers

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.


The | in JavaScript is an integer bitwise OR operator. In that context, it strips off any fractional portion returned by parseFloat. The expression parseFloat($(this).val()) will result in a number with (potentially) a fractional component, but then |0 will convert it to an integer number, OR it with 0 (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.5 becomes -1, and 1.5 becomes 1. This is like Math.floor, but truncating rather than rounding "down" (Math.floor(-1.5) is -2 — the next lowest whole number — rather than -1 as the |0 version 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 |):

Total += parseFloat($(this).val()) || 0;

That defends against the possibility that $(this).val() returns "" or similar, resulting in parseFloat returning NaN. It uses the curiously-powerful || operator to return 0 rather than NaN in 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 to Total, or if they were just defending the NaN case.