can I avoid the evail to convert from string to a boolean

C

Carlos Aguayo

Hi,
Is there a better way to do this?
The problem that I have is that x can be "true" or "false" (as type
string), or true or false (as boolean type). I'm doing comparisons
like...

if (eval(x) == true){
// do something...
}

or..

if (eval(x) == false){
// do something...
}

I'd like to get rid of the eval, I tried to use the !!, but if I do !!x
when x is "false", it returns true since it's not an empty string. Do
you know a better way to do this? Without forcing x to be always a
string or always a boolean?

Thanks,
Carlos
 
W

web.dev

Carlos said:
Hi,
Is there a better way to do this?
The problem that I have is that x can be "true" or "false" (as type
string), or true or false (as boolean type). I'm doing comparisons
like...

if (eval(x) == true){
// do something...
}

or..

if (eval(x) == false){
// do something...
}

I'd like to get rid of the eval, I tried to use the !!, but if I do !!x
when x is "false", it returns true since it's not an empty string. Do
you know a better way to do this? Without forcing x to be always a
string or always a boolean?

Though it's redundant to do so on a string, you can do the following:

if(x.toString() == "true")
{
//etc.
}

[...]

if(x.toString() == "false")
{
//etc.
}

This will work for both booleans and strings.
 
D

Dr John Stockton

JRS: In article <[email protected]>,
dated Fri, 6 Oct 2006 16:49:42 remote, seen in
news:comp.lang.javascript said:
Is there a better way to do this?
Yes.

The problem that I have is that x can be "true" or "false" (as type
string), or true or false (as boolean type).

Within a program, away from I/O, a logical value with exactly two
significantly-different states should be a Boolean, and not a String.

You should convert the value to genuine Boolean as soon as it is
generated, if it is not already Boolean. The type will be known at
creation.

You should not ask your users to put "true" or "false" in a control that
inputs strings; you should use a checkbox instead.

If you are obliged to accept such strings, then convert to lower case,
compare with both "true" and "false", and decide what to do if neither
match.

It's a good idea to read the newsgroup and its FAQ. See below.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top