Domanda

I checked the following code in JSLint:

<!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

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 parentheses when && has a higher precedence than ||? I can simply remove nested parentheses instead of:

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


Please correct me if I'm mistaken.

È stato utile?

Soluzione

JSLint is designed to produce more human-readable code, using the rules defined by whoever wrote JSLint (which may be based on other peoples' opinion, but ultimately is just opinion)

Therefore, !== is more human-readable than != because it makes it obvious that the comparison is strict. However, you know different because ta.value and ta.defaultValue are indeed always strings, so you aren't required to follow JSLint's advice.

Similarly, parenthesising the && expression makes it more human-readable, because it makes it clear what order things are run in. While you may know order of precedence, not everyone does at a glance and may interpret it wrong.

To restate, JSLint is advice and opinion, not law.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top