Recently I was running some of my code through JSLint when I came up with this error. The thing I think is funny about this error though is that it automatically assumes that all == should be ===.
Does that really make any sense? I could see a lot of instances that you would not want to compare type, and I am worried that this could actually cause problems.
The word "Expected" would imply that this should be done EVERY time.....That is what does not make sense to me.
IMO, blindly using ===, without trying to understand how type conversion works doesn't make much sense.
The primary fear about the Equals operator == is that the comparison rules depending on the types compared can make the operator non-transitive, for example, if:
A == B AND
B == C
Doesn't really guarantees that:
A == C
For example:
'0' == 0; // true
0 == ''; // true
'0' == ''; // false
The Strict Equals operator === is not really necessary when you compare values of the same type, the most common example:
if (typeof foo == "function") {
//..
}
We compare the result of the typeof operator, which is always a string, with a string literal...
Or when you know the type coercion rules, for example, check if something is null or undefinedsomething:
if (foo == null) {
// foo is null or undefined
}
// Vs. the following non-sense version:
if (foo === null || typeof foo === "undefined") {
// foo is null or undefined
}
JSLint is inherently more defensive than the Javascript syntax allows for.
From the JSLint documentation:
The == and != operators do type coercion before comparing. This is bad because it causes ' \t\r\n' == 0 to be true. This can mask type errors.
When comparing to any of the following values, use the === or !== operators (which do not do type coercion): 0 '' undefined null false true
If you only care that a value is truthy or falsy, then use the short form. Instead of
(foo != 0)
just say
(foo)
and instead of
(foo == 0)
say
(!foo)
The === and !== operators are preferred.
Keep in mind that JSLint enforces one persons idea of what good JavaScript should be. You still have to use common sense when implementing the changes it suggests.
In general, comparing type and value will make your code safer (you will not run into the unexpected behavior when type conversion doesn't do what you think it should).
Triple-equal is different to double-equal because in addition to checking whether the two sides are the same value, triple-equal also checks that they are the same data type.
So ("4" == 4) is true, whereas ("4" === 4) is false.
Triple-equal also runs slightly quicker, because JavaScript doesn't have to waste time doing any type conversions prior to giving you the answer.
JSLint is deliberately aimed at making your JavaScript code as strict as possible, with the aim of reducing obscure bugs. It highlights this sort of thing to try to get you to code in a way that forces you to respect data types.
But the good thing about JSLint is that it is just a guide. As they say on the site, it will hurt your feelings, even if you're a very good JavaScript programmer. But you shouldn't feel obliged to follow its advice. If you've read what it has to say and you understand it, but you are sure your code isn't going to break, then there's no compulsion on you to change anything.
You can even tell JSLint to ignore categories of checks if you don't want to be bombarded with warnings that you're not going to do anything about.
A quote from http://javascript.crockford.com/code.html:
=== and !== Operators.
It is almost always better to use the
=== and !== operators. The == and != operators do type coercion. In
particular, do not use == to compare
against falsy values.
JSLint is very strict, their 'webjslint.js' does not even pass their own validation.
If you want to test for falsyness. JSLint does not allow
if (foo == null)
but does allow
if (!foo)
To help explain this question and also explain why NetBeans (from) 7.3 has started showing this warning this is an extract from the response on the NetBeans bug tracker when someone reported this as a bug:
It is good practice to use === rather than == in JavaScript.
The == and != operators do type coercion before comparing. This is bad because
it causes ' \t\r\n' == 0 to be true. This can mask type errors. JSLint cannot
reliably determine if == is being used correctly, so it is best to not use ==
and != at all and to always use the more reliable === and !== operators
instead.
Reference
Well it can't really cause problems, it's just giving you advice. Take it or leave it. That said, I'm not sure how clever it is. There may well be contexts in which it doesn't present it as an issue.
You can add this to the previous line to disable these warning.
// eslint-disable-next-line
Related
Although there are semantic differences between JavaScript's null and undefined, many times they can be treated as the same. What's the preferable way of checking if the value is either null or undefined?
Right now I'm doing the following:
if (typeof value === "undefined" || value === null) {
// do something
}
Which is pretty verbose. I could, of course, create a function for this and import everywhere, but I'm wishing that there's a better way to achieve this.
Also, I know that
if (value == null) {
}
Will get the job done 90% of the time, unless value is zero... or false... or a number of implicit things that can cause obscure bugs.
Also, I know that
if (value == null) {
}
Will get the job done 90% of the time, unless value is zero... or false... or a number of implicit things that can cause obscure bugs.
No, it gets the job done 100% of the time. The only values that are == null are null and undefined. 0 == null is false. "" == undefined is false. false == null is false. Etc. You're confusing == null with falsiness, which is a very different thing.
That's not to say, though, that it's a good idea to write code expecting everyone to know that. You have a perfectly good, clear check in the code you're already using. Whether you choose to write value == null or the explicit one you're currently using (or if (value === undefined || value === null)) is a matter of style and in-house convention. But value == null does do what you've asked: Checks that value is null or undefined.
The details of == are here: Abstract Equality Comparison.
underscore js has a function for this _.isUndefined()
from https://underscorejs.org/#isUndefined
isUndefined _.isUndefined(value)
Returns true if value is undefined.
example:
_.isUndefined(window.missingVariable);
=> true
lodash has a similar function. see https://lodash.com/docs/4.17.11#isUndefined
Both have similar functions for isNull too.
I find the functions are useful for others to know what is being tested for.
I am implementing a seemingly trivial utility function to check if a value is null or undefined.
My original implementation looked like this:
function isNil(value) {
return value === null || value === undefined;
}
I then looked up Lodash's implementation:
function isNil(value) {
return value == null
}
On the surface, this would seem like a naiive approach since it violates eslint's eqeqeq rule as well as only checking for null.
I'm guessing that this approach works due to a combination of JavaScript's truthiness and equality rules, but is there actually an advantage to Lodash's implementation?
value === null || value === undefined and value == null are equivalent as can be seen in the specification of the Abstract Equality Comparison Algorithm:
The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:
[...]
If x is null and y is undefined, return true.
If x is undefined and y is null, return true.
The "eqeqeq" rule of ESLint is not relevent as it is just for linting, it does not enforce anything in ECMAScript itself. And lodash does not use that rule.
Technically, there is no real advantage as it has the exact same outcome. One might argue value == null could be faster as it does only do one equality check and does not perform up to two calls of the Strict Equality Comparison Algorithm like your first example. It does most probably not matter at all as even if there was a difference, it would be very small.
Personally, I would use the value === null || value === undefined as it is clearer and does not even need a documentation. Besides, tools like uglify could easily replace value === null || value === undefined with value == null for production.
The two expressions seem to be functionally equivalent (source). Thus lodash's implementation would be preferable just because it requires slightly fewer comparisons.
Although there are semantic differences between JavaScript's null and undefined, many times they can be treated as the same. What's the preferable way of checking if the value is either null or undefined?
Right now I'm doing the following:
if (typeof value === "undefined" || value === null) {
// do something
}
Which is pretty verbose. I could, of course, create a function for this and import everywhere, but I'm wishing that there's a better way to achieve this.
Also, I know that
if (value == null) {
}
Will get the job done 90% of the time, unless value is zero... or false... or a number of implicit things that can cause obscure bugs.
Also, I know that
if (value == null) {
}
Will get the job done 90% of the time, unless value is zero... or false... or a number of implicit things that can cause obscure bugs.
No, it gets the job done 100% of the time. The only values that are == null are null and undefined. 0 == null is false. "" == undefined is false. false == null is false. Etc. You're confusing == null with falsiness, which is a very different thing.
That's not to say, though, that it's a good idea to write code expecting everyone to know that. You have a perfectly good, clear check in the code you're already using. Whether you choose to write value == null or the explicit one you're currently using (or if (value === undefined || value === null)) is a matter of style and in-house convention. But value == null does do what you've asked: Checks that value is null or undefined.
The details of == are here: Abstract Equality Comparison.
underscore js has a function for this _.isUndefined()
from https://underscorejs.org/#isUndefined
isUndefined _.isUndefined(value)
Returns true if value is undefined.
example:
_.isUndefined(window.missingVariable);
=> true
lodash has a similar function. see https://lodash.com/docs/4.17.11#isUndefined
Both have similar functions for isNull too.
I find the functions are useful for others to know what is being tested for.
This is from Crockford's JavaScript: The Good Parts
var is_array = function (value) {
return Object.prototype.toString.apply(value) === '[object Array]';
};
Would this code have worked just as well if he had used a simple equality compare == instead of the identity compare ===?
My understanding of identity is that it allows you to check if a value is really set to something specific, and not just something equivalent. For example:
x == true
Will evaluate to true if x is 1, or true, but
x === true will only be true if x is true.
Is it ever possible for the is_array function above to work with either == or ===, but not the other?
In this particular case == and === will work identically.
There would be no real difference in this case because both sides of the quality test are already strings so the extra type conversion that == could do won't come into play here. Since there's never any type conversion here, then == and === will generate the same result.
In my own personal opinion, I tend to use === unless I explicitly want to allow type conversion as I think there is less likelihood of getting surprised by some result.
You are correct. With == instead of === it should work fine.
=== is a strict match, and will not return true for 'falsy' or 'truthy' values (see this for more details). Which shouldn't apply in this situation.
I was checking out JSLint, and some of the rules piqued my interest. Particularly this:
Disallow == and !=
Disallow ++ and --
Why is it a bad idea to disallow these? I understand the first part, basically it wants me to do === instead of ==. I don't understand why though. I understand the difference between the two, I just want to know why is it bad practice. Some times I really want to do == for example so that it would evaluate true for undefined == null
The second one, well I don't understand at all. Does it want me to do myInt += 1 instead of myInt++ ?
Thanks!
I don't agree too much with those rules, instead of discouraging the use of ==, I would recommend to learn about type coercion.
The primary reason about why Crockford wants to avoid == is that the comparison rules depending on the types of the operands can make this operator non-transitive, for example, if:
A == B AND
B == C
Doesn't guarantees that:
A == C
A real example:
'0' == 0; // true
0 == ''; // true
'0' == ''; // false
The strict === operator is not really necessary when you compare values of the same type, for example:
if (typeof foo == "function") { }
We compare the result of the typeof operator, which is always a string, with a string literal...
Another example, when you compare something against null, == also compares against undefined, for example:
if (something == null) {}
VS
if (something === null || typeof something === "undefined") {}
The above two conditions are at the end equivalent, but the first one much more readable, of course if you know about type coercion and how == behaves.
Learning how the == operator works, will help you to wisely decide which to use.
Recommended articles:
ECMAScript. Equality operators (Great tips to remember how == works)
typeof, == and ===
Doug Crockford has his own ideas about what is "good" and "bad" in Javascript. Accordingly, JSLint implements these checks, but makes them optional if you don't completely agree with him.
Disallowing == helps prevent you from making mistakes when you really meant ===. Of course this assumes that you never really want to use ==.
Disallowing ++ and -- is a style thing, some people believe they are harder to read than += 1 and -= 1.
Douglas crockford (the guy who wrote JSLint) explains himself in this video :
http://www.youtube.com/watch?v=hQVTIJBZook#t=14m45s
but basically (as everyone else has mentioned) it's because of the type coercian.
Worth watching the who video to be honest - very interesting and useful.
From the instructions:
The == and != operators do type coercion before comparing. This is bad because it causes ' \t\r\n' == 0 to be true. This can mask type errors.
and
The ++ (increment) and -- (decrement) operators have been known to contribute to bad code by encouraging excessive trickiness. They are second only to faulty architecture in enabling to viruses and other security menaces. There is a plusplus option that prohibits the use of these operators.
The == and != operators do implicit converson of the operators if needed, while the === and !== operators don't. The expression 4 == '4' for example will be true, while the expression 4 === '4' will be false.
Preferrably you should know the data types you are dealing with, so that you can do the proper comparisons in the code.
The ++ and -- operators doesn't cause any problems if they are used alone in a statement, but they are often used to make a statement that does more than one thing in a not so obvious way, like:
arr[++idx] = 42;
which would be clearer as:
idx += 1;
arr[idx] = 42;
The behavior of the standard equality operators (== and !=) depends on the JavaScript version. So that's one reason for not using them.
Another reason is that the behavior of the = tends to be very vague.
See https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Comparison_Operators
I understand ==. (the undefined == null thing is an exception)
("0" == false) === true
("0" === false) === false
I've never understood the ++ and -- thing though. I don't like doing i+=1 all over my code (it's slower than ++i).