How to do this if a condition evaluates its value in javascript

Like javascript if a condition defines its value ?, see this example:

<script type="text/javascript">

var bar = ("something" == true);
alert(bar); // 1

if ("something") {
    alert("hey!"); // 2
}

</script>

Why am I getting the point // 2, and the "bar" in // 1 is false?

As I can see, the value is barcalculated almost the same as the if condition, or is it not?

+5
source share
5 answers

This is because of the way the coercion mechanism like javascript works. When you say

"something" == true

javascript calls ToNumber on your "something" to compare it with a boolean. "something" produces NaN, which is not true.

However

if("something")

checks the correctness of the string. Since this is not an empty string, this is truly true.

: http://webreflection.blogspot.co.il/2010/10/javascript-coercion-demystified.html

+2

"something" == true , , . if("something") , .

+4

, JavaScript (lit. "something" == "true"), .

"something", true.

. .

+1
if("something")

true, "something" . false, (""). (0 false, 1 true).

"something"==true , ( "-" == "", false).

+1

, javascript , , javascript .

, true. , "something != false, true.

- JavaScript, .

:

"something" !== false // true
"something" === true  // false
"" === false          // false
0 === false           // false

To find out about this, there are lots of articles. I would recommend Douglas Crockford .

0
source

All Articles