I'm trying to find out how to suppress the eslint error in my javascript code.
Local variable 'rtn' is redundant
I found the documentation for this here: https://eslint.org/docs/rules/no-useless-return
The docs say:
If you don't care about disallowing redundant return statements, you can turn off this rule.
But don't say how to disable this error. The only example they give is having it enabled: /* eslint no-useless-return: "error" */.
I'm new to eslint so how do I do this? I've tried
/* eslint no-useless-return: "suppress" */
export function dateToYYYYMMDD(theDate : Date, separator = "-") : string {
const rtn = theDate.getFullYear() + separator
+ ("0" + (theDate.getMonth() + 1)).substr(-2) + separator
+ ("0" + theDate.getDate()).substr(-2);
return rtn;
}
but this didn't work. I tried other values like "ok" but that didn't work. What is the right value to use?
The same question but for Java is here: "Local variable is redundant" using Java. The Java annotation @SuppressWarnings("UnnecessaryLocalVariable") does not work in Javascript. :-)
I think you can solve it inline like this:
// eslint-disable-next-line no-useless-return
export function dateToYYYYMMDD(theDate : Date, separator = "-") : string {
.....
this comment must be on top of the line where the error happens.
or you can create an eslint configuration file like .eslintrc.json and disable it in the rules, for example:
{
"globals": {
"__DEV__": "readonly"
},
"env": {
"es2021": true
},
"extends": [
....
],
"plugins": [
....
],
"rules": {
"no-useless-return": "off"
}
}
or you can return the expression directly instead of storing it in a constant
There is no need to declare a variable and then immediately return it - just return the expression itself without assigning it to a variable first.
export function dateToYYYYMMDD(theDate : Date, separator = "-") : string {
return theDate.getFullYear() + separator
+ ("0" + (theDate.getMonth() + 1)).substr(-2) + separator
+ ("0" + theDate.getDate()).substr(-2);
}
So, first thing is, if you want to disable a rule in ESLint, please refer to: https://eslint.org/docs/user-guide/configuring/rules#disabling-rules
Second, it doesn't seem like that specific rule warning makes sense in your code - I have tried to reproduce it in here (ESLint Demo) and I get no messages whatsoever after turning no-useless-return on.
You might want to double-check your IDE and see if this is really coming from ESLint.
I know that an extension such as SonarLint would catch such a thing so you have to check your editor to see what's triggering the message you got.