PDA

View Full Version : Two errors I get in JSLint for no good reason



Rain Lover
03-31-2014, 03:32 PM
I checked the following code in JSLint (http://www.jslint.com/):


<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title>Reset textarea</title>
</head>

<body>
<textarea id="ta">
<p>Hello</p>
</textarea>
<input type="button" value="Reset" onclick="reset();">
<script>
function reset() {
var ta = document.getElementById('ta');
if (!ta.value || ta.value != ta.defaultValue && confirm('Are you sure?')) {
ta.value = ta.defaultValue;
}
}
</script>
</body>

</html>

DEMO (http://jsfiddle.net/Mori/e2Fzm/)

And I got the following errors:


Expected '!==' and instead saw '!='.

Since the textarea value and default value are always of the type string, then there's no type conversion before comparison and it makes absolutely no difference except making your JS file larger!


The '&&' subexpression should be wrapped in parens.

Why should I add parenthesis when && has a higher precedence (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table) than ||? I can simply remove nested parenthesis (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Removing_nested_parenthesis) instead of:


if (!ta.value || (ta.value != ta.defaultValue && confirm('Are you sure?')))

Please correct me if I'm mistaken.

traq
03-31-2014, 07:17 PM
there's no type conversion before comparison and it makes absolutely no difference except making your JS file larger!
One extra equals sign is not a significant difference in file size. Are you minifying your scripts and html markup? That would be a much larger bandwidth savings.

Generally speaking, triple equals (or bang-double equals) should always be used, unless you specifically want type conversion. JSLint marks this as an error because it is a very common source of hard-to-find mistakes (many coders simply don't understand the difference between == and === in the first place; and even experienced programmers can easily overlook it).


Why should I add parenthesis when && has a higher precedence …?
Because, as above, precedence is a major cause of unexpected behaviors. Even if you arranged it correctly, as desired, it's harder to read clearly and you risk errors cropping up if you ever have to modify the code.

So, to answer your question: no, you're not mistaken, and your code is not really "wrong."

But yes, JSLint did point those issues out for a good reason. JSLint looks for best practices, not technical correctness. It's reminding you to make your code obviously correct.