Re: if question
From: Steve Fulton (cerberus40_at_hotmail.com)
Date: 03/14/05
- Next message: Jeff North: "Re: Slow Jscript objects response with large number of objects"
- Previous message: Arvind: "Slow Jscript objects response with large number of objects"
- In reply to: Lithium: "Re: if question"
- Next in thread: Lasse Reichstein Nielsen: "Re: if question"
- Reply: Lasse Reichstein Nielsen: "Re: if question"
- Reply: RobB: "Re: if question"
- Messages sorted by: [ date ] [ thread ]
Date: Mon, 14 Mar 2005 07:46:20 -0500
Lithium wrote:
> "Lasse Reichstein Nielsen" wrote:
>>
>> If instead you write
>> ---
>> if (x == true) ...
>> ---
>> then "x == true" is evaluated. First "x" evalutes to the string "test",
>> then, since "test" and true are different types, type conversion is
>> performed before comparing. In this case, both are converted to numbers,
>> which is NaN and 0 respectively, and these are compared and not equal.
>
> Let me see if i get it... an empty string to Boolean converted gives false
> all other strings gives true.
>
> because if (x) ...requires a boolean inside the string is automatically
> converted to boolean..thats clear...
>
> but
> if (x==true) ...the string isnt converted to boolean although a boolean
> stands on the right ... they are both converted to numbers..,,which in my
> opinion makes no sense..
However, it's just your opinion. I don't have the patience to wade through
the ECMA-262 (ECMAScript) spec to find out exactly what should happen in
this circumstance, but you're welcome to:
Standard ECMA-262, "ECMAScript Language Specification"
http://www.ecma-international.org/publications/files/ecma-st/ECMA-262.pdf
> why convert both to numbers when you only have to convert one to the other
> and boolean is the simplest type.
Why convert the string to boolean? Why not convert the boolean to string?
Then you get:
true.toString() yields "true".
"test" != "true".
Therefor, x != true.
If you don't want the JScript interpreter deciding which type should be
converted, you can explicitly convert the string:
if (Boolean(x) == true)
However, I've never understood this strange need some people have to
compare a Boolean result to true or false in if statements. As we've
seen, it accomplishes nothing when it works as expected and leads to
errors when it doesn't. A simple "if (x)" or "if (!x)" is sufficient.
-- Steve If men could regard the events of their own lives with more open minds, they would frequently discover that they did not really desire the things they failed to obtain. -Emile Herzog
- Next message: Jeff North: "Re: Slow Jscript objects response with large number of objects"
- Previous message: Arvind: "Slow Jscript objects response with large number of objects"
- In reply to: Lithium: "Re: if question"
- Next in thread: Lasse Reichstein Nielsen: "Re: if question"
- Reply: Lasse Reichstein Nielsen: "Re: if question"
- Reply: RobB: "Re: if question"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|