The JavaScript Code Quality Tool
See all
Members (560)
Douglas Crockford's profile photo
Andy Dawson's profile photo
Abhisek Roy's profile photo
Adam Moore's profile photo
Andrew Ryan's profile photo
Adhithya Rajagopalan's profile photo
ahmd refat's profile photo
Ahmed Attyah's profile photo
Antonio Cunha Santos's profile photo
Albert Wiersch's profile photo
Andrew Pennebaker's profile photo
Ara Pehlivanian's profile photo
Alex Howard's profile photo
Andrii Trybynenko's profile photo
Andreas Stankewitz (Naradana)'s profile photo
Alexandr Cherednichenko's profile photo
Alexandre Canijo's profile photo
Alexandre Morgaut's profile photo
Alfredo Delgado's profile photo
Angelos Chaidas's profile photo
amruta shah's profile photo
Anas Bihi's profile photo
Angelo Cicero's profile photo
Andi Mario Rumahombar's profile photo

Stream

 
The "browser" option should not allow to use the "parent" global variable, which is a reference to the global object.
https://github.com/douglascrockford/JSLint/blob/bab010bdc3080cdfd6375c7d7574ae45684de2d0/jslint.js#L150
1
Douglas Crockford's profile photo
 
Right.
Add a comment...

Pascal Bilodeau

Discussion  - 
 
Hello everybody,

When a thisArg parameter is provided to forEach(), I have in the called function a JSlint error "Unexpected 'this'.".

Example :
/*jslint browser: true */

/**
 * Affecte la visibilité d’un élément du DOM
 *
 *@param element objet HTML
 */
function affecterVisibilite(element) {
    "use strict";
    element.style.visibility = this;
}

/**
 * Affiche une classe
 *
 *@param classe chaîne nom de la classe
 */
function afficherClasse(classe) {
    "use strict";
    Array.from(document.getElementsByClassName(classe)).forEach(affecterVisibilite, "visible");
}

-------------------------------------------
I can check tolerate this but is this the only way ?
 ·  Translate
1
Peter's profile photoPascal Bilodeau's profile photo
2 comments
 
Thank you very much Peter.
Add a comment...
 
JSLint says "Bad assignment to 'this'." and V8 yells "ReferenceError: Invalid left-hand side in assignment" at this code:
/*jslint this */
function GetObject() {
    "use strict";
    this.selfDestruct = function () {
        this = undefined;
    };
}
The equivalent of this piece of code without using "this":
function getObject() {
    "use strict";
    var object = {
        selfDestruct: function () {
            object = undefined;
        }
    };
    return object;
}
Nobody yells at it. I think JSLint should give the "Bad assignment to 'object'." warning here on line 4.
1
Peter's profile photoЕвгений Орехов (Evgeny Orekhov)'s profile photo
14 comments
 
+Peter I'm just a beginner! :D
Add a comment...

Denis Sidorov

Discussion  - 
 
Здравствуйте! Работаю с ссылочными типами (классы), обнаружил следующее:
Код:

if (typeof Array.isArray === "undefined") {
    Array.isArray = function (arg) {
        "use strict";
        return Object.prototype.toString.call(arg) === "[object Array]";
    };
}
Ошибка JSLint:
Unexpected 'typeof'. Use '===' to compare directly with undefined.
-------------------------------------------------------------------

Книга Херман Дэвид Сила - JavaScript. 68 способов эффективного использования JS. (страница 38)
Рассмотрим функцию, которой могут передаваться необязательные аргументы, имеющие значения по умолчанию:
function point(x, y) {
if (!x) {
x = 320;
}
if (!y) {
y = 240;
}
return { x: x, y: y };
}
Эта функция игнорирует любые ложные аргументы, в том числе 0:
point(0, 0); // { x: 320, y: 240 }

Более точный способ проверки факта отсутствия определения заключается в использовании оператора typeof:
function point(x, y) {
if (typeof x === "undefined") {
x = 320;
}
if (typeof y === "undefined") {
y = 240;
}
return { x: x, y: y };
}
Эта версия функции point правильно отличает 0 от
undefined:
point(); // { x: 320, y: 240 }
point(0, 0); // { x: 0, y: 0 }
Еще один подход заключается в сравнении со значением
undefined:
if (x === undefined) { ... }

Для тестирования неопределенных значений нужно использовать оператор typeof или выполнять сравнение со значением undefined, а не выполнять проверку на истинность.

Книга Стоян Стефанов - JavaScript. Шаблоны (страница 75)
if (typeof Array.isArray === “undefined”) {...
 ·  Translate
1
Евгений Орехов (Evgeny Orekhov)'s profile photoDenis Sidorov's profile photo
2 comments
 
Евгений, огромное Вам спасибо за комментарий!
 ·  Translate
Add a comment...

Peter Funk

Discussion  - 
 
Is there a way to suppress the "Quotes are not needed around 'myKey'" warning?
var myJSONObject = {
    "myKey": "myValue"
};
1
Peter Funk's profile photoPeter's profile photo
3 comments
Peter
 
use JSON.stringify to convert
Add a comment...
 
There is a convention to prefix variable names and property names that hold a jQuery object with $, for example:
var $button = jQuery("button");
// or
app.$button = jQuery("button");
JSLint is OK with $ in variable names but not in property names.
Would you consider allowing $ in property names?
2
Douglas Crockford's profile photo
 
Put the $names in a /property/ declaration.
Add a comment...
 
An example from JSLint source:
...
} else {
    if (open) {
        var at = free
            ? margin
            : margin + 8;
        if (right.from < at) {
            expected_at(at);
        }
    } else {
        if (right.from !== margin + 8) {
            expected_at(margin + 8);
        }
    }
}

could be simplified to:
} else if (open) {
    var at = free
        ? margin
        : margin + 8;
    if (right.from < at) {
        expected_at(at);
    }
} else if (right.from !== margin + 8) {
    expected_at(margin + 8);
}

I'd like JSLint to not expect another "if" as the only statement in an else block.
1
Douglas Crockford's profile photo
 
'else if' can sometimes obscure the true structure, making modification more difficult.
Add a comment...
 
function f(x) {
    "use strict";
    if (x === 0) {
        return 1;
    } else {
        return 2;
    }
}

"Unnecessary 'else' after disruption" warning is missing for the above code.
1
Douglas Crockford's profile photoЕвгений Орехов (Evgeny Orekhov)'s profile photo
2 comments
 
+Douglas Crockford Too bad. I will miss this warning.
I noticed that JSlint doesn't expect "else if" after disruption, but expects "else", I think that's just inconsistent.
Add a comment...

Austin Cheney

Discussion  - 
 
Indentation concerning strings wrapped with a "+" does not appear uniform.

var a = {
        cat: "r:#00c;font-weight:bold;height:auto;left:14em;margin:0;overflow:hidden;position:" +
                ":block}#announcement.normal{color:#000;font-weight:normal;height:2.5em;margin:0 "
    },
    b = [
        "r:#00c;font-weight:bold;height:auto;left:14em;margin:0;overflow:hidden;position:" +
        ":block}#announcement.normal{color:#000;font-weight:normal;height:2.5em;margin:0 "
    ];
if (a.length > 0) {
    a = "r:#00c;font-weight:bold;height:auto;left:14em;margin:0;overflow:hidden;position:" +
            ":block}#announcement.normal{color:#000;font-weight:normal;height:2.5em;margin:0 ";
}

In the above code we can see that strings when wrapped with a "+" operator expect two steps of indentation when they are a product of assignment whether by "=" or as an object property.  The same wrapping expects only 1 step of indentation when in an array index.

I would suspect that either the array get the same indentation as provided to the object literal because they are both containers, or that the array index get the same level of indentation as the "=" assignment because they both do not have the depth of property names.
1
Austin Cheney's profile photoDouglas Crockford's profile photo
8 comments
 
Did you look at the fudge option?
Add a comment...

About this community

This group is for discussion of JSLint, including feature requests, complaints, update announcements, and testimonials.
 
I heard that there was "Variable might not have been initialized" error in Java. Why isn't there such warning in JSLint? Is there more good than harm in having "maybe uninitialized" variables in your code?
http://stackoverflow.com/questions/2448843/variable-might-not-have-been-initialized-error
1
Douglas Crockford's profile photoЕвгений Орехов (Evgeny Orekhov)'s profile photo
4 comments
 
+Douglas Crockford Here: https://github.com/douglascrockford/JSLint/blob/master/jslint.js#L1215 the "i" variable is definetely uninitialized when you access it here https://github.com/douglascrockford/JSLint/blob/master/jslint.js#L1368
and it is uninitialized every time you access it after this if block if the condition is falsy https://github.com/douglascrockford/JSLint/blob/master/jslint.js#L1371
What happens is you get "line 0 column NaN" if you put this in JSLint:
/*/
Add a comment...

Nathan Ho

Discussion  - 
 
angular.forEach($scope.items, function (value, item) {
    // some code using only the "item" variable
});

If I have a callback function with two arguments, but I don't use the first, then JSLint warns of an unused variable. I don't think this is sensible because you might only use some of the arguments in someone else's API.
1
Nathan Ho's profile photoBen Quarmby's profile photo
3 comments
 
Yes, JSLint only allows "ignore" once per scope. Ignoring a lot of arguments is a sign that something is wrong.

When it comes to third party libraries with code smell (like callbacks with many potentially unused arguments), it may be necessary to wrap them in something more sensible.
Add a comment...

Peter Funk

Discussion  - 
 
(myNumber + '').replace('5', '2');
('' + myNumber).replace('5', '2');

These give the warning "Unexpected '.'.".
Should it actually say "Don't use '+' to convert variables into strings." since "myNumber.toString().replace('5', '2');" passes?
1
Евгений Орехов (Evgeny Orekhov)'s profile photo
 
The "Unexpected '.'" warning is about promoting the use of variables, e. g.
var myString = myNumber + '';
myString.replace('5', '2');
Add a comment...

Peter

Discussion  - 
 
Unexpected 'arguments'.

var simpleConcat = function () {
    "use strict";
    return Array.slice(arguments).join(' ');
};

i understand arguments is not part of the good parts, but sometimes it is necessary example: printf or console.log etc...
is there any alternatives for them?
2
Ben Quarmby's profile photoFedge No's profile photo
5 comments
 
I'd work around this one by just accepting an object as the only argument to the function. Maybe that wouldn't work for all cases but it's a more versatile way to pass some data and doesn't involve any weirdness in trying to figure out what you're looking at.
Add a comment...

Harry Whitfield

Discussion  - 
 
/*jslint eval, devel */
var formula = "sin(x)";
var x = Math.PI / 6;
with (Math) {
    alert(eval(formula));   // 0.5
}

produces 4 warnings.

It might be better to just say "Don't use with!".
1
Douglas Crockford's profile photo
 
Right you are.
Add a comment...
 
y = x
    ? true
    : false;

JSLint warns that it expected '!!' and instead saw '?', but what about this example:
if (x) {
    y = true;
} else {
    y = false;
}

Shouldn't JSLint also warn that this should be simplified to
y = !!x;

I guess one can argue that the former version is more maintainable, but in my opinion it makes the whole program less maintainable just because it is more complex.
1
Евгений Орехов (Evgeny Orekhov)'s profile photoAustin Cheney's profile photo
3 comments
 
I would say this warning is completely justified but perhaps it could use a better explanation in either its language or in the documentation.  I couldn't figure it out until I posted something similar here a couple of days ago.  The end goal here is to eliminate boolean assignment through a ternary as a similar warning appears even if the default value is false instead of true.

If the default value is true the ternary can be kept as an assignment to its condition and simply removing the ternary part:

var a = (b > 1) ? true : false;  //always the same if removing `? true : false`

When the default is false the condition has to be reversed, but the same rule applies:

var a = (b === false || b === "false") ? false : true; //bad
var a = (b !== false && b !== "false"); //good
Add a comment...

Nathan Ho

Discussion  - 
 
/*jslint . */

A syntax error in a JSLint directive returns a weird warning that simply says 'bad_directive_a'.
1
Douglas Crockford's profile photo
 
Thanks. Please try it now.
Add a comment...
 
if (a !== undefined) {
    doThis();
} else {
    doThat();
}

It would've been nice if JSLint warned that a negated "if" that has "else" branches should be inverted to increase the clarity of the statement:
if (a === undefined) {
    doThat();
} else {
    doThis();
}
1
Евгений Орехов (Evgeny Orekhov)'s profile photo
10 comments
 
+Douglas Crockford Looks like I was wrong in the previous comment, that would be NPath complexity that would be affected by eliminating elses in a program, not cyclomatic complexity.
Add a comment...