I believe double equal to is no need, when we have triple equal to (===).
Am i right?
Please clear me on this with simple/good example.
Thanks.
I believe double equal to is no need, when we have triple equal to (===).
Am i right?
Please clear me on this with simple/good example.
Thanks.
Well it depends. It does something different I think ==
is only considered bad because it goes against the convention but sometimes having automatic type coercion can be a nice piece of syntactic sugar. As long as the person writing it and the people reading it are clear about what is going on it's perfectly acceptable. It's especially good if you want to take advantage of things that are truthy or falsey statements. The MDN does a good job of explaining the concept of sameness in javascript
The difference is:
An example :
'1' == 1 // true
'1' === 1 // false
==
double equal is not exact value
var a = 10;
if(a == "10"){
alert('true'); // will work fine
}
===
is check variable cast e.g. integer
if(a === "10"){
alert('false'); // will not work
}
The double equal does type coercion, which may come in handy, especially if you're trying to do numeric comparisons against DOM values, which are always strings. For example:
var num = document.getElementById('numericField').value;
if( num===3 ) {
// this will never be reached, even if the user enters '3'
}
if( num==3 ) {
// this will be reached if the user enters '3'
}
if( Number(num)===3 ) {
// this will also work
}