Home > Web Front-end > JS Tutorial > How Does the Tilde Operator Affect Conditional Expressions in JavaScript?

How Does the Tilde Operator Affect Conditional Expressions in JavaScript?

Susan Sarandon
Release: 2024-11-27 20:54:14
Original
243 people have browsed it

How Does the Tilde Operator Affect Conditional Expressions in JavaScript?

Conditional Expression with Preceding Tilde Operator

In JavaScript, a tilde (~) operator can precede an expression to perform bitwise negation. When working with conditional expressions, this operator can have a specific use.

Example Code:

var attr = ~'input,textarea'.indexOf( target.tagName.toLowerCase() )
           ? 'value'
           : 'innerHTML'
Copy after login

Explanation:

The indexOf() function returns -1 if the target value is not found. By negating this value using the ~ operator, we effectively convert it to truthy (any non-zero value) for matches and falsy (-1) for non-matches.

Bitwise Operation:

In JavaScript, numbers are internally represented as 32-bit integers. The ~ operator flips all the bits in its operand, effectively inverting them.

For instance, if the value of 'input,textarea'.indexOf( target.tagName.toLowerCase() ) is 1 (representing the character 'i'), its binary representation would be:

0000 0000 0000 0000 0000 0000 0000 0001
Copy after login

Applying the ~ operator flips all the bits, resulting in:

1111 1111 1111 1111 1111 1111 1111 1110
Copy after login

The resulting value is -2 in 2's complement representation.

Conditional Outcome:

In the conditional expression, the value of ~'input,textarea'.indexOf( target.tagName.toLowerCase() ) is evaluated to determine whether to assign 'value' or 'innerHTML' to the attr variable. If the target is found, the expression will evaluate to truthy, resulting in 'value' being assigned to attr. Otherwise, if the target is not found, the expression will evaluate to falsy, resulting in 'innerHTML' being assigned to attr.

The above is the detailed content of How Does the Tilde Operator Affect Conditional Expressions in JavaScript?. 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