PDA

View Full Version : === instead of ==



carlitos_way
Mar 29th, 2007, 12:41 PM
Hi all,

i have seen in many js codes the notation === used instead of ==, can you tell me which is the difference from them? before using js, i had never seen it.. :confused:

Philip M
Mar 29th, 2007, 01:03 PM
A visit to http://www.javascriptkit.com/jsref/operators.shtml explains that:

== Tests for equality in value between two operands. e.g. 3==8
Result: returns false.

=== Tests for equality between two operands both in terms of value and type. (Supported in JavaScript 1.3+) Using x=3 and y="3":

1) x==y
Result: returns true

2) x===y
Result: returns false

carlitos_way
Mar 29th, 2007, 01:21 PM
ok, but for example, look at the code we have here

/* toggle an element's display */
function toggle(obj) {
var el = document.getElementById(obj);
if (el.style.display == 'block') {
el.style.display = 'none';
el.style.visibility = 'hidden';
} else {
el.style.display = 'block';
el.style.visibility = 'visible';
}
}

i pasted it on jslint (http://www.jslint.com/), and it gave me this error:

Error:

Problem at line 4 character 26: Use '===' instead of '=='.

if (el.style.display == 'block') {

the compare is between an attribute (display) and a string (block). why do the sintax '===' should return true?

liorean
Mar 29th, 2007, 01:58 PM
JSLint suggest the best practice coding.

If you want a string comparison with a string, then you should use === instead of == because there is no risk of accidental automatic conversion of the the value from some other type to string.

1212jtraceur
Mar 29th, 2007, 02:02 PM
the compare is between an attribute (display) and a string (block). why do the sintax '===' should return true?

Correction: the compare is between a property value and a string. Since the property value is a string (or at least, should be...), '===' does just fine.

carlitos_way
Mar 29th, 2007, 03:14 PM
Correction: the compare is between a property value and a string. Since the property value is a string (or at least, should be...), '===' does just fine.

yes, i was thinking it was something like this... thanks;)