How does javascript if condition determines its value?, see this example:
<script type="text/javascript">
var bar = ("something" == true);
alert(bar); // 1
if ("something") {
alert("hey!"); // 2
}
</script>
Why do I get to point //2 while 'bar' at //1 is false?
As I can see bar
value gets calculated in almost the same way the if condition, or it doesn't?
The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. The if/else statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions.
The IF statement executes one set of code if a specified condition is met (TRUE) or another set of code evaluates to FALSE.
OR – =IF(OR(Something is True, Something else is True), Value if True, Value if False) NOT – =IF(NOT(Something is True), Value if True, Value if False)
An if statement is a programming conditional statement that, if proved true, performs a function or displays information. Below is a general example of an if statement, not specific to any particular programming language. if (X < 10) { print "Hello John"; }
"something" == true
is false because the string and the boolean have to be coerced into types that can be compared. However, if("something")
works because a non-empty string is a truthy value.
It's because of how the javascript type coercion engine works. When you say
"something" == true
javascript calls ToNumber on your "something" string to compare it to the boolean. "something" produce NaN which does not equal true.
However
if("something")
only checks if the string is truthy. Because it's not an empty string, it is in fact truthy.
More here: http://webreflection.blogspot.co.il/2010/10/javascript-coercion-demystified.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With