How to use the logical NOT operator In Javascript
The logical NOT operator in Boolean algebra is used to negate an expression or value. Using this operator on a true value would return false and using it on a false value would return true. This property can be used to toggle a boolean value. The NOT operator is used before the variable is toggled and the result is assigned to the same variable. This will effectively toggle the boolean value.
Syntax:
booleanValue = !booleanValue
Example: We are using the logical NOT operator
html
< html > < head > < title > How to toggle a boolean using JavaScript? </ title > </ head > < body > < h1 style = "color: green" > w3wiki </ h1 > < b > How to toggle a boolean using JavaScript? </ b > < p > The boolean is toggled whenever the button is pressed. </ p > < p > See the console for the output </ p > < button onclick = "toggle()" > Toggle Bool </ button > < p id = "toggled" > </ p > < script > let testBool = true; function toggle() { testBool = !testBool; let text = document.getElementById('toggled') text.innerHTML = testBool } </ script > </ body > </ html > |
Output:
How to toggle a boolean using JavaScript ?
A boolean value can be toggled in JavaScript by using two approaches which are discussed below:
Table of Content
- Using the logical NOT operator
- Using the ternary operator
- Using the XOR (^) operator