Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does if condition evaluates its value in javascript

Tags:

javascript

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?

like image 847
Jaime Hablutzel Avatar asked Jul 18 '12 16:07

Jaime Hablutzel


People also ask

How if condition works in JavaScript?

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.

What does an if statement evaluate?

The IF statement executes one set of code if a specified condition is met (TRUE) or another set of code evaluates to FALSE.

How do you write an if or condition?

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)

What does mean in if condition?

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"; }


2 Answers

"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.

like image 102
Niet the Dark Absol Avatar answered Oct 27 '22 15:10

Niet the Dark Absol


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

like image 26
just.another.programmer Avatar answered Oct 27 '22 16:10

just.another.programmer