6

I know the difference between == and === however I always believed that if (condition) condition was supposed to be evaluated against true using strict equality (===) and not type-coercing equality (==).

See an example:

if (1) {
    console.log("1");
}

if (1 == true) {
    console.log("2");
}

if (1 === true) {
    console.log("3");
}

It returns:

::1
::2

I know 1 is not strictly equal to true, because the type is different, but when I do if (condition) according to W3C it should be the strict equality test (===) that is run not the type-coercing equality of ==.

So why is it logging 1?

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
amandanovaes
  • 694
  • 2
  • 7
  • 20
  • 2
    Please clarify **when I do if (condition) according to W3C it should be === not ==** – Matteo Tassinari Jul 26 '13 at 14:15
  • 1
    http://longgoldenears.blogspot.com/2007/09/triple-equals-in-javascript.html – Vinit Prajapati Jul 26 '13 at 14:16
  • When I do "if (1)" according to W3C it should be interpreted as "if (1 === true)" instead of "if (1 == true)" which is what happens on Chrome – amandanovaes Jul 26 '13 at 14:16
  • are you talking about your first example? `1` is a truthy value, only falsy values are `undefined`, `null`, `0`, `''` and `false` (but not the string `'false'`) – Dennis Jul 26 '13 at 14:17
  • 5
    Where does the W3C specify that? – deceze Jul 26 '13 at 14:17
  • @Glauco: where did you read that? – Matteo Tassinari Jul 26 '13 at 14:17
  • @VinitPrajapati as I said, I already know very well the difference of == and ===. – amandanovaes Jul 26 '13 at 14:17
  • 2
    no, `if(1)` should not be `if (1 === true)`. Those kind of `if (condition)` will only check if `condition` is a truthy value. – Dennis Jul 26 '13 at 14:18
  • 1
    This question has been asked many time and answer many times too. I believe this is the original question.http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons please refer and get your doubts clarified – AnaMaria Jul 26 '13 at 14:18
  • 1
    @AnaMaria: I think this question is slightly different, the OP is asking whether the default comparison used in browser is `==` or `===` – Matteo Tassinari Jul 26 '13 at 14:19
  • 2
    Where did you see that W3C said it was === ? – Fiona - myaccessible.website Jul 26 '13 at 14:19
  • 6
    If you say _according to W3C_ you do realize that W3C has nothing to do with JavaScript. The specs for JS are maintained by ECMA. Also note that W3C !== W3schools, nor W3C != w3schools... not even close – Elias Van Ootegem Jul 26 '13 at 14:20
  • @MatteoTassinari YOU ARE the ONLY ONE who undestood my question! – amandanovaes Jul 26 '13 at 14:23
  • @MatteoTassinari, if you check the link I sent, this question has been answered extensiviley there, There are about 30 replies. Some of these replies are far better than the W3C recommendations. So if the question is genuine im sure that refering to that link will give the OP a better answer – AnaMaria Jul 26 '13 at 14:23
  • 2
    "in the browser" is not relevant - the standard for JavaScript has nothing to do with browsers. – Pointy Jul 26 '13 at 14:24
  • 1
    The relevant specification are the [Ecmascript one](http://www.ecma-international.org/ecma-262/5.1/Ecma-262.pdf). The relevant section for your question is the section 12.5 – HoLyVieR Jul 26 '13 at 14:25
  • @AnaMaria I am sorry to disagree with you but the link http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons has nothing to do with my question. I wanna know the default bejaviour of the browser which should be === – amandanovaes Jul 26 '13 at 14:25
  • 1
    @Glauco: Deceze and (in all modesty) my answer deal with the behaviour of JS, not the difference between the operators – Elias Van Ootegem Jul 26 '13 at 14:31
  • My book says it very clear that W3C stands if (condition) as if (condition === true). Maybe it applies to some conditional statement that can be done with CSS. – amandanovaes Jul 26 '13 at 14:33

9 Answers9

11

The if statement uses condition == true. It's given in the ECMAScript Language Specification, here: http://www.ecma-international.org/ecma-262/5.1/#sec-12.5

Note the usage of the ToBoolean() in Step 2. This converts the given argument to a Boolean value, meaning that yes, type coercion does occur for the condition of an if statement.

Serlite
  • 12,130
  • 5
  • 38
  • 49
  • 4
    I just have a comment on this, people on StackOverflow dont read the question right, and downvote it so quick without understanding... if you did not understand the question it's your problem, read again or make a comment instead of downvoting. This answer provided by @Serlite SAVED me. Now I can teach my classmates this default behaviour that in my book sayed the default of W3C is ===. Or the book is wrong or the book is talking about W3C === in CSS cause as you told me javascript specification is on ECMAS not W3C. – amandanovaes Jul 26 '13 at 14:31
  • 6
    @Glauco: What book states that _according to W3C_ the default behaviour is `===`? Please tell me, so I can blacklist it for eternity, and hold a ritual burning, in case I ever rule the world ;) – Elias Van Ootegem Jul 26 '13 at 14:33
  • 2
    @Glauco While I did understand your original question, I can see why people got confused. One thing that really helps is the context. If we had known that you were trying to work out whether something in a book you have is wrong and is misleading your classmates, it may have been clearer. Just trying to help :) – Fiona - myaccessible.website Jul 26 '13 at 14:34
  • @EliasVanOotegem Sir, in my book says (translating from portuguese to bad my english): W3C states if (condition) will always be if (contition === true), meaning value and type must match. From the answers I got in this page, probably this explanation has to do with CSS cause you prooved me that W3C has nothing to do with JAVASCRIPT. I still just do not know where in CSS is possible to make a comparson. Do you know if there is some whay (like a ternary in a style sheet) to make a comparson? – amandanovaes Jul 26 '13 at 14:37
  • 1
    @Glauco Well, either the book is talking about Javascript or it's talking about CSS. If it's that easy to get the context confused or if the book itself messes up ECMA with the W3C, you should probably throw it out. – deceze Jul 26 '13 at 14:39
  • @deceze The name of the book is "Mastering CSS". It only talks about CSS and W3C specification all time. But I thought that the explanation about the if (condition) sayed in the book would be the same in JS. Thank you anyway. – amandanovaes Jul 26 '13 at 14:41
  • 1
    @Glauco: In CSS, you can add something like `[if IE 6]background: url('get_real.png') no-repeat center center;` in your CSS. – Elias Van Ootegem Jul 26 '13 at 14:42
  • @EliasVanOotegem you are right. I did not remember this comparson. But you proved my book is wrong, cause [if IE 6] is matching only the value not the type since IE -> "6" not 6. Thank you! I will send an email to the editor of the book correcting that statement with the link of this page. – amandanovaes Jul 26 '13 at 14:48
  • 1
    @Glauco: Note that `[if gt IE 6]background: url('nogood_browser.png');` is possible, too. But still, the condition is only met when it can be resolved to `true`, and will never be met if, for some reason, the browser type cannot be determined to the fullest. Edited my answer to include the CSS bit, will add tag to your question, too – Elias Van Ootegem Jul 26 '13 at 14:53
5

Javascript a.k.a. ECMAScript is not governed by the W3C but by ECMA. You can read the specification here. What you're interested in is this section, which specifies how expressions in if statements are handled. The runtime should call toBoolean on the expression value; meaning any type is going to be converted to a boolean.

Therefore it behaves like ==.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • Your answer is probably the only one that is answering what I asked. But I did not find the section in the link you provided confirmim that the default behaviour is == and not === – amandanovaes Jul 26 '13 at 14:27
  • 2
    The behavior is given as **"If ToBoolean(GetValue(exprRef)) is true..."**. It's a language specification, not a tutorial. They don't use the term "`==`". `ToBoolean()` is the method to convert any type to a boolean, meaning there's type conversion going on, meaning it *behaves like `==`*. – deceze Jul 26 '13 at 14:29
4

Because === is strict comparison operator.

if (1 === true) { //they are of a different type

Have you tried this

if (0) {  // This fails
    console.log("1");
}

because 0 = off, negative, no, false universally. check this Why is 0 false?

whereas whereas when you use ===

if( 1 === true)  //It looks for type 1 as number and true as boolean

ES5 spec defines the following algorithm:

enter image description here

Community
  • 1
  • 1
Praveen
  • 55,303
  • 33
  • 133
  • 164
  • So does this means it is trying to compare a numeric value to a boolean? Which will return false. – Pais Jul 26 '13 at 14:28
  • @Pais yes, you're right. `===` belongs to **left-to-right** associativity. so it will check as you mentioned. – Praveen Jul 26 '13 at 14:47
4

As you're getting this info from a book on CSS, the author is most likely referring to CSS rules like this:

[if IE]body
{/* only for IE*/
    [if IE 6] background: url('get_real.gif');
    [if gt IE 6] background: url('nogood_browser.png');
}
[if Webkit]body
{/*Only webkit browsers get this bg*/
    background: url('webkit_bg.png');
}
[if Gecko]body
{/*Gecko-based browsers get this*/
   background: url('foxy.png');
}

Other than that - On JS:

My guess would be you got the idea from the place all mis-information comes from. Please, for your sake and mine, don't use w3schools.

in case of an if (condition), where condition should read expression to be correct, it should be truthy, if the expression consists of a single value. In case you are comparing 2 expressions, the conditional expression evaluates to true or false, based on how you compare the two operands

Single operand:

if (1)//truthy
if (undefined) //falsy

This is because Boolean(1) === true and Boolean(undefined) === false
Once you introduce a second operand:

if ('0' == 0)//=== true
if ('0' === 0)// === false

That's because === is a type and value check, which you obviously know already. Just so there's no confusion:

If you want to be sure you have the correct information: check the ECMAScript language specs, not some third party resource: here's the link

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
3

It is equivalent to condition == true, which is specified by ECMAScript Language Specification

sasha.sochka
  • 14,395
  • 10
  • 44
  • 68
  • Where could you confirm this information Sir? That if (condition) means if (condition == true) instead of if (condition === true) – amandanovaes Jul 26 '13 at 14:20
  • 1
    @Glauco, shouldn't it be clear from all the comments that you misread some document, or that the document you read was incorrect? – Pointy Jul 26 '13 at 14:22
  • as @MatteoTassinari sayed I want to know the default behaviour used by the compiler which should be a comparson of value and type, not only value when i do if (condition) – amandanovaes Jul 26 '13 at 14:24
  • @Glauco you are mistaken. It is **not** supposed to be `===`. – Pointy Jul 26 '13 at 14:25
3

The 3 equal signs mean "equality without type coercion". Using the triple equals, the values must be equal in type as well.

Difference between == and === in JavaScript

Community
  • 1
  • 1
Vinit Prajapati
  • 1,593
  • 1
  • 17
  • 29
1

Truthy: Something which evaluates to TRUE. Falsey: Something which evaluates to FALSE.

1 is truthy, 0 is falsey.

An object of any kind (including functions, arrays) is always truthy.

These are all falsy: undefined, null, NaN, 0, "" (empty string), and false.

Hence, in your first condition if (1)... logs 1 because 1 is truthy.

=== specifically tests for type equality, which is different from testing truthy.

Abhitalks
  • 27,721
  • 5
  • 58
  • 81
0

I found the section in the ECMA documentation on ToBoolean, which is used in the if statement.

To summarise:

Number : The result is false if the argument is +0, −0, or NaN; otherwise the result is true.

Fiona - myaccessible.website
  • 14,481
  • 16
  • 82
  • 117
0

Note: there's a simple way to convert an expression to Boolean and it is using !! operator. For Example
!!1 is true
!!{} is true
!!"" is false and !!"asdf" is true
so i always feel comfortable converting expressions to Boolean and then letting them into an if comparison test

if (1) { // !!1 is true and anything non-zero is true even -ve numbers just like c language
    console.log("1");
}

if (1 == true) { //!! 1 is true and we are not checking type only two equals (==)
    console.log("2");
}

if (1 === true) { //!! 1 is true but the type is number which is obviously not a Boolean type
    console.log("3");
}
Mateen
  • 1,631
  • 1
  • 23
  • 27