Reputation:
Consider the following snippet of code
if(word.startsWith("bool"))
{
s = word.split(" ");
return s+" "+ Boolean(s[1]);
}
Examples
word ="bool 12>3" ==> true
word ="bool 1>3" ==> false
for queries such as bool 1>2 function says true. but if I use it in console, it says the correct answer.
Upvotes: 1
Views: 527
Reputation: 781004
Boolean()
simply performs type conversion, it doesn't evaluate code. When converting a string to boolean, an empty string becomes false
, a non-empty string becomes true
.
If you want to evaluate the word, you have to call eval()
.
return s+" "+ Boolean(eval(s[1]));
Note that using eval()
can be dangerous if the data comes from an untrusted source, since this will be able to execute any JavaScript functions.
When you type Boolean(1>3)
in the console, 1>3
is evaluated as an expression by the console, it's not a string. To see the same problem in the console, enter Boolean("1>3")
, since word
is a string, not an expression that has already been evaluated.
Upvotes: 2