javascript boolean change value

Javascript Boolean Change Value

Boolean is a data type in Javascript which can have two values: true or false. Sometimes, we need to change the boolean value based on certain conditions. In this blog post, I will explain how to change the boolean value in Javascript.

Method 1: Using the NOT operator (!)

The easiest way to change the boolean value in Javascript is by using the NOT operator. The NOT operator is represented by an exclamation mark (!) and it flips the boolean value. For example:


let boolValue = true;
boolValue = !boolValue;
console.log(boolValue); // false

In the above example, we have initialized a boolean variable boolValue with a value of true. We then use the NOT operator to flip the boolean value and assign it back to the same variable. Finally, we log the updated value of the variable which is false.

Method 2: Using the Comparison Operator (===)

We can also change the boolean value in Javascript by comparing it with another value using the comparison operator (===). The comparison operator returns a boolean value which can be assigned to a variable. For example:


let num1 = 10;
let num2 = 20;
let boolValue = num1 === num2;
console.log(boolValue); // false

In the above example, we are comparing two variables num1 and num2 using the comparison operator. Since num1 is not equal to num2, the comparison operator returns false which is then assigned to the variable boolValue.

Method 3: Using the Ternary Operator (? :)

The last method to change the boolean value in Javascript is by using the ternary operator. The ternary operator is represented by a question mark followed by a colon (? :). It is a shorthand way of writing an if-else statement. For example:


let num1 = 10;
let num2 = 20;
let boolValue = (num1 === num2) ? true : false;
console.log(boolValue); // false

In the above example, we are using the ternary operator to check if num1 is equal to num2. If it is, then the ternary operator returns true, otherwise it returns false. The returned value is then assigned to the variable boolValue.

These are three different ways to change the boolean value in Javascript. You can use any of these methods depending on your use case.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe