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.
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 .
Successive commands only execute if preceding ones succeed. Similarly, || will allow the successive command to execute if the preceding fails.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With