Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrong conversion of error to a boolean value #7141

Closed
agigleux opened this issue Jul 23, 2020 · 1 comment
Closed

Wrong conversion of error to a boolean value #7141

agigleux opened this issue Jul 23, 2020 · 1 comment

Comments

@agigleux
Copy link
Contributor

agigleux commented Jul 23, 2020

Hello,

I scanned the code with SonarCloud and discovered this pattern is often used:

const hasError = error && error !== null;

I found it complicated to understand and I believe the code is not doing what you expect, especially when error is null or undefined.
I think the code could be change to:

const hasError = !!error;
or
const hasError = Boolean(error);

Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean#:~:text=Do%20not%20use%20a%20Boolean

Reproducer:

 var error = {"description": "blabla", "code": 2};
 var hasError = error && error !== null;
 console.log(hasError); // true

 var error = "blabla";
 var hasError = error && error !== null;
 console.log(hasError); // true

 var error = null;
 var hasError = error && error !== null;
 console.log(hasError); // null: while false is expected

 var error;
 var hasError = error && error !== null;
 console.log(hasError); // null: while false is expected
 

 var error = {"description": "blabla", "code": 2};
 var hasError = !!error;
 console.log(hasError); // true

 var error = "blabla";
 var hasError = !!error;
 console.log(hasError); // true

 var error = null;
 var hasError = !!error;
 console.log(hasError); // false

 var error;
 var hasError = !!error;
 console.log(hasError); // false
@soupette
Copy link
Contributor

Thanks a lot @agigleux for spotting these kind of improvements. Do you mind creating a PR to fix them?

agigleux added a commit to agigleux/strapi that referenced this issue Jul 24, 2020
agigleux added a commit to agigleux/strapi that referenced this issue Jul 24, 2020
Signed-off-by: agigleux <alexandre.gigleux@sonarsource.com>
gilfernandes pushed a commit to onepointconsulting/strapi that referenced this issue Aug 13, 2020
Signed-off-by: agigleux <alexandre.gigleux@sonarsource.com>

Co-authored-by: Alexandre BODIN <alexandrebodin@users.noreply.github.com>
Signed-off-by: Gil Fernandes <gil.fernandes@onepointltd.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants