How to use the ternary operator In Javascript
The ternary operator is used as a shortcut to using the if/else statement. It is used to make a decision based on the condition of expression. It takes three parameters, the condition statement, the expression to be executed if the condition is satisfied and the expression to be executed if the condition is not satisfied. The boolean value to be toggled is passed as the condition. The expression to be executed if true is given as ‘false’ and expression to be executed if false is given as ‘true’. The result of this operator is assigned back to the boolean value to be toggled. This will effectively toggle the value as a true condition will return false, and a false condition would return true.
Syntax:
booleanValue = booleanValue? false : true
Example: We are using the ternary operator
html
<!DOCTYPE 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 > < button onclick = "toggle()" > Toggle Bool </ button > < p id = "toggled" > </ p > < script > let testBool = true; console.log('Default value of bool is', testBool); function toggle() { testBool = testBool ? false : true; 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