convert variable from string to boolean in Javascript
Code snippet on how to convert variable from string to boolean in Javascript
const stringToBool = (str) => {
if (str === 'true') return true;
if (str === 'false') return false;
return str;
};
This code snippet provides a function, called “stringToBool”, that takes in a single argument called “str”. It then checks to see if the value of “str” is either “true” or “false”. If it is, it will return either true or false respectively. If “str” is neither “true” nor “false”, it will return the original variable. This way, it is possible to convert any string variable to its corresponding boolean variable.