Home  >  Article  >  Web Front-end  >  What is the Double Tilded Operator (~~) in JavaScript and How Does It Compare to Math.floor()?

What is the Double Tilded Operator (~~) in JavaScript and How Does It Compare to Math.floor()?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 09:05:02228browse

What is the Double Tilded Operator (~~) in JavaScript and How Does It Compare to Math.floor()?

Double Tilded Operator (~~) in JavaScript

Question:

In certain code samples, the "double tilde" (~~) operator is encountered. What is its purpose and how does it differ from the Math.floor() function?

Answer:

The ~~ operator is a Double Bitwise NOT operator. It provides a faster and positive numeric result than the Math.floor() function.

The Double Bitwise NOT operation converts the number to a 32-bit integer, then applies the bitwise NOT operator (~) twice. The resulting value is:

~~x = -(~~~x + 1)

Since the ~ operator flips the 0s and 1s in the bit pattern, the ~~ operation effectively strips the decimal part of the positive number by truncating it towards zero.

Differences from Math.floor() Function:

While can be used as a faster substitute for Math.floor() for positive numbers, it does not yield the same result for negative numbers. simply chops off the decimal part, while Math.floor() rounds down to the nearest integer.

Example:

console.log(~~2.3); // Output: 2 (equivalent to Math.floor(2.3))
console.log(~~-2.3); // Output: -2 (different from Math.floor(-2.3) which equals -3)

The above is the detailed content of What is the Double Tilded Operator (~~) in JavaScript and How Does It Compare to Math.floor()?. 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