Home >Web Front-end >JS Tutorial >Why Does `0.5 | 0` Evaluate to 0 in JavaScript?

Why Does `0.5 | 0` Evaluate to 0 in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-27 05:28:30588browse

Why Does `0.5 | 0` Evaluate to 0 in JavaScript?

Exploring the Bitwise Operation in JavaScript: The Curious Case of ""|"

In JavaScript, the single pipe character ""|"" represents the bitwise or operation. This operator performs a logical evaluation on the binary representations of its operands and outputs a binary value with bit positions set to 1 if either operand has a corresponding bit set to 1.

To understand how this operator works, let's consider an example:

<code class="js">console.log(0.5 | 0); // 0
console.log(-1 | 0); // -1
console.log(1 | 0); // 1</code>

Surprisingly, 0.5 | 0 evaluates to 0, while -1 | 0 and 1 | 0 both return their input integers. This behavior arises because JavaScript's bitwise operations only operate on integers. When 0.5 is passed to the | operator, it is truncated to 0, leaving us with 0 | 0, which results in 0.

In contrast, both -1 and 1 are integers. The bitwise or operation sets the corresponding bits to 1 if either operand has that bit set. Since both -1 and 1 have all their bits set to 1, the operation simply returns the input integers: -1 | 0 returns -1, and 1 | 0 returns 1.

In essence, the single pipe operator performs a bitwise or operation, which sets bits to 1 if either input has a corresponding bit set to 1. However, since bitwise operations only apply to integers, JavaScript truncates non-integer operands, potentially altering the output of the operation.

The above is the detailed content of Why Does `0.5 | 0` Evaluate to 0 in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn