+ 1

How change String to boolean?

I wanna pass something logical and return it. "1 > 2" //return false "true" // return false "0" // return false "1" // return true. Reason: I was kiddimg today try some comparisom, so I was doing: console.log("Test: " + "1 > 2" + ((1>2)?true:false)); But all time writing the string I'm testing and again on (condition), I want just improve: var varTest = " 1 > 2"; console.log("test: " + varTest + ((toBool(varTest)?true:false)). (Because I'm using function, and typing two parameter one as String and other as boolean, I want pass one parameter and convert it.

23rd Oct 2020, 7:51 PM
Marcelo Anjos
Marcelo Anjos - avatar
2 Answers
+ 4
start with this code: function myfunc(input){ if (input == "false"){ return false } if (input == "true"){ return false } }
23rd Oct 2020, 10:28 PM
Galaxy-Coding (inactive)
Galaxy-Coding (inactive) - avatar
+ 3
The only way to do that is to evaluate the string as code. A way to do that is using eval or Function constructor: https://code.sololearn.com/cEcA9O42bD7p/?ref=app
23rd Oct 2020, 10:54 PM
Kevin â˜