JSLint Messages – Bad Assignment

JSLint prompts you with this message when it encounters what it perceives to be a dangerous, or “bad” assignment. For example:

document.getElementById("text"+x) = function(){};

In the above code, we are calling a function, and then attempting to assign it a value. Clearly the case of document.getElementById() nonsense anyway, and will fail. It doesn’t shed any light as to how this sort of error might occur, so let us look an example with custom objects.

It is possible to create a function within a JavaScript object in many ways. The following demonstrates one such scenario:

var obj = { fn : function () {}};

No problems here. But what if we wanted an ad-hoc creation (possibly as part of some sort of desire to extend an existing object)? We might see something resembling the following:

var obj2 = {};
obj2.fn = function () {};

Again, no problem. However it is conceivable that we might encounter the following (entered, perhaps, by accident):

var obj2 = {};
obj2.fn() = function () {};

Do you spot the subtle difference? The developer has stipulated an extra set of brackets. It will certainly not what was intended, but has found its way into the code. When JSLint encounters this, will complain about a bad assignment.

But, in JavaScript, object members can also be referenced using the array/collection [] notation. Happily, JSLint is clever enough to spot this. So the following will yield the same error (along with another JSLint error [{a}] is better written in dot notation):

document["getElementById"]("test") = function(){};

A Guide To JSLint Messages

This article is one of a series on the error and warning messages produced by JSLint.

One thought on “JSLint Messages – Bad Assignment

  1. Pingback: JSLint – A Guide To JSLint Messages | James Wiseman

Leave a Reply