Home > Web Front-end > JS Tutorial > body text

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

Mary-Kate Olsen
Release: 2024-11-01 09:05:02
Original
227 people have browsed it

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)
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!