"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > ## What Does the Double Tilde Operator (~~) Do in JavaScript?

## What Does the Double Tilde Operator (~~) Do in JavaScript?

Published on 2024-11-17
Browse:101

## What Does the Double Tilde Operator (~~) Do in JavaScript?

Double Tilde Operator in JavaScript (~~)

In JavaScript, the ~~ operator is a type coercion operator that removes everything after the decimal point of a number. This differs from the ~ operator, which is a bitwise NOT operator that inverts the bits of a value.

Operation

The operator works by first converting its operand to a signed 32-bit integer. This means that even if the operand is a floating-point number or a string, it will be treated as an integer internally. The operator effectively performs the following:

  • If the operand is negative, it rounds up to the next integer (Math.ceil).
  • If the operand is positive, it rounds down to the next integer (Math.floor).

Usefulness

While the ~~ operator may seem like a simple replacement for Math.floor or Math.ceil, it has some limitations:

  • It can result in overflow if the operand is outside the range of -(2^31) to 2^31 - 1.
  • It is not suitable for non-integer operands, as it ignores the decimal portion.

Therefore, it is generally recommended to use x (unary plus) or Number(x) for type coercion, and Math.floor or Math.ceil for rounding.

Example

Consider the number -43.2:

  • ~~(-43.2) = -43
  • Math.floor(-43.2) = -44

As you can see, ~~ rounds toward zero while Math.floor rounds down. This behavior can be useful in certain scenarios, such as truncating a number without using a decimal point.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3