Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why 'Unexpected "."' when using || operator for a default value in parenthesis

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.

like image 588
ciso Avatar asked Jan 18 '16 01:01

ciso


People also ask

What does '!' Mean in Javascript?

symbol is used to indicate whether the expression defined is false or not. For example, !( 5==4) would return true , since 5 is not equal to 4. The equivalent in English would be not .

What is the purpose of ||?

Successive commands only execute if preceding ones succeed. Similarly, || will allow the successive command to execute if the preceding fails.


1 Answers

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

like image 140
guest271314 Avatar answered Nov 12 '22 09:11

guest271314