I’ll introduce methods for converting strings to Boolean in JavaScript.
Prerequisites
This assumes converting values passed through URL parameters or POST requests to Boolean type.
Approach: true as "1", false as ""
By treating true as some string (in this case “1”) and false as an empty string "", you can convert to Boolean using the !! idiom.
!!'1'; // true
!!''; // false
Approach: true as "true", false as "false"
Another approach is to use exact string matching to compare “true” and “false” strings.
var param = "true";
param === "true" ? true : false; // true
var param = "false";
param === "true" ? true : false; // false
var param = "";
param === "true" ? true : false; // false
Personally, I think Boolean true/false and string “true”/“false” are hard to distinguish at a glance, which reduces readability and can be a source of bugs.
However, when using Vue.js or similar on the client side to handle Boolean values and sending POST requests to the server side, you would probably use this approach for conversion.
Defining a toBoolean Method
You can also define a toBoolean method to convert from String to Boolean type.
/**
* Returns Boolean from string representing Boolean
*
* Returns true if s is 'true' or '1', false if 'false' or '0',
* otherwise returns the value of def
*
* @param {String} s String representing Boolean
* @param {unknown} def Value to return when s is neither 'true' nor 'false'
*
* @return {Boolean} or def
*/
var toBoolean = function(s, def) {
switch (s) {
case 'true':
case '1':
case 'on':
return true;
case 'false':
case '0':
case 'off':
return false;
}
return def;
};
Summary
Converting from string to Boolean type is something that inevitably comes up when implementing web applications, so there might be good Node.js methods or npm modules for this.
Reference Information
That’s all from the Gemba.