Ad

Why 'Unexpected "."' When Using || Operator For A Default Value In Parenthesis

- 1 answer

Getting Unexpected "." from jslint ( http://jslint.com/ ) on this code:

function test(foo) {
    "use strict";
    return (foo || "").replace("bar", "baz");
}

Why does jslint have a problem with the || operator to force an empty string so a replace can be performed without causing an error, in case foo is passed in as undefined?

This passes:

function test(foo) {
    "use strict";
    var xFoo = (foo || "");
    return xFoo.replace("bar", "baz");
}

I know it's opinion based and I can ignore it, etc... but trying to understand why chaining like this is frowned upon. Also know about eshint, but I'm not trying to get around this message, just want to understand why.

Seems like the first approach is more concise and cleaner since it doesn't need the extra variable (xFoo).

Both functions do exactly the same thing under all conditions.

Ad

Answer

Using String()contructor removes error at jslint

function test(foo) {
    "use strict";
    return String(foo || "").replace("bar", "baz");
}

See also Distinction between string primitives and String objects , JSLint Help

Ad
source: stackoverflow.com
Ad