1

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.

5
  • please add word and the wanted result. Commented Feb 22, 2020 at 18:25
  • Boolean() will not evaluate the expression. Any non-empty string is true. Commented Feb 22, 2020 at 18:27
  • But I use the same function in console which giving me correct answers Commented Feb 22, 2020 at 18:28
  • 1
    Did you type a string? Boolean("1>3")? Commented Feb 22, 2020 at 18:29
  • 1>3 is not the same as "1>3". The console evaluates expressions. Commented Feb 22, 2020 at 18:29

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

yeah this is working . But why the Boolean is not working in code but working in js console
I just added an explanation to the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.