user2807681 user2807681 - 5 months ago 24
Javascript Question

JS: How to fix "Expected ')' to match '(' from line 4 and instead saw '='." JSLint error

I have written the following function:

function MyTest(element, no, start=0) { = no;
this.element = element;
this.currentSlide = start;


JSLint complains:

Expected ')' to match '(' from line 4 and instead saw '='.

What is wrong with this? Is it the default value I've set?


JavaScript doesn't have default values for arguments (yet; it will in the next version, and as Boldewyn points out in a comment, Firefox's engine is already there), so the =0 after start is invalid in JavaScript. Remove it to remove the error.

To set defaults values for arguments, you have several options.

  1. Test the argument for the value undefined:

    if (typeof start === "undefined") {
        start = 0;

    Note that that does not distinguish between start being left off entirely, and being given as undefined.

  2. Use arguments.length:

    if (arguments.length < 3) {
        start = 0;

    Note, though, that on some engines using arguments markedly slows down the function, though this isn't nearly the problem it was, and of course it doesn't matter except for very few functions that get called a lot.

  3. Use JavaScript's curiously-powerful || operator depending on what the argument in question is for. In your case, for instance, where you want the value to be 0 by default, you could do this:

    start = start || 0;

    That works because if the caller provides a "truthy" value, start || 0 will evaluate to the value given (e.g., 27 || 0 is 27); if the caller provides any falsey value, start || 0 will evaluate to 0. The "falsey" values are 0, "", NaN, null, undefined, and of course false. "Truthy" values are all values that aren't "falsey".