Boolean() function that permits users to convert other types to a boolean type. We can exploit this function to convert a string to a boolean.
In this way, non-empty objects are evaluated as “
true” even if the string value is “false”.
let myString1="LearnShareIt"; console.log(Boolean(myString1)); let myString2="false"; console.log(Boolean(myString2));
Empty objects like:
false are evaluated as “false”.
console.log(Boolean(false)); // False console.log(Boolean(0)); // False console.log(Boolean(NaN)); // False console.log(Boolean("")); // False console.log(Boolean(null)); // False console.log(Boolean(undefined)); // False
False False False False False False
Using Logical NOT (!) operator
The ! compel value we need to convert to a boolean, but it will reverse the result, so if we want to invert the result back, we have to put another !. The !! operator returns the same result as the
Try using the ! operator
let myString1 = ""; console.log(!myString1); let myString2 = "LearnShareIt"; console.log(!myString2);
Because of the reverse result caused by the ! operator leads to 2 opposite consequences:
myString1 is “” with the result will be “
false” but now we receive “
myString2 is “LearnShareIt” as a result will be “
true” but the ! operator converts the outcome into “
Now try using the !! operator
let myString1 = ""; console.log(!!myString1); let myString2 = "LearnShareIt"; console.log(!!myString2);
An !! operator will reverse the result of the ! operator
Using Identity Operator (===)
The identity operator is known as a strict operator. This operator will validate the value and the type of the operands. It only compares two values and returns true if they are compared and have the same value and type. We can use the identity operator to convert a string to a boolean by comparing the string that needs to be converted with “true”. This way will return a boolean true if the string is actually “true” and return a boolean false with others.
// Try with the string "true". let myString1 = "true"; let boolValue1= (myString1 === "true"); console.log(boolValue1); // Try with other string let myString2 = "false"; let boolValue2= (myString2 === "true"); console.log(boolValue2);"
Boolean() function or logical NOT (!) operator are both accessible and convenient, these approaches will return a boolean true if the string is not empty even if the string value is “false”. You may want a different result.