DEV Community

Discussion on: TIPS & TRICKS OF JAVASCRIPT & REACT

Collapse
lukeshiru profile image
Info Comment hidden by post author - thread only visible in this permalink
LUKESHIRU • Edited

Disagree with pretty much every tip here. They are just "hacky/smarty" ways of doing things that make the code less readable, less maintenable and less secure:

  • Tip 1: You shouldn't do that at all. You should make your intent obvious with functions like parseFloat or parseInt.
  • Tip 2: Again, you should use functions like Math.ceil, Math.floor, and Math.round depending on what you want to round and how.
  • Tip 3: You should never rely in globals like that, because they are quite easy to manipulate in the user side.
  • Tip ?: Short-circuiting is not a good practice. Is less clear than using just an if or a ternary.
  • Tip 4: Is way better to use ??: value ?? "default".
  • Tip 5: Bitwise operators shouldn't be used for stuff like rounding, again, check Tip 2.
  • Tip 6: You can resolve the performance issue by running the function when is matched:
    ({
        1: doSomething,
        2: doSomethingElse,
        3: doSomethingElseAndOver
    }[something])?.();
Enter fullscreen mode Exit fullscreen mode
  • Tip 7: You can just use Array.prototype.includes: [1,5,7].includes(x).
  • Tip 8: This one is actually descent. Generally is better to have a single argument of type object. The only thing to fix is that you mixed old with new syntax, it should look something like this:
const myFunction = ({ param1, param2, param3, param4 }) =>
    console.log(param1, param2, param3, param4);

myFunction({ param1: 1, param2: 2, param3: 3, param4: 4 });
Enter fullscreen mode Exit fullscreen mode
  • Tip 9: That code you used actually doesn't work because you can't return a throw, instead what you can do is this:
const myFunction = value =>
    console[value ? "log" : "error"](
        value ? "You have a value" : "You don't have a value"
    );

// Or maybe use a Promise to make it more flexible:

const myFunction = value =>
    new Promise((resolve, reject) =>
        value ? resolve("You have a value") : reject("You don't have a value")
    );

myFunction(1).then(console.log).catch(console.error);
Enter fullscreen mode Exit fullscreen mode

Overall, you should consider that making the code "shorter" is not making it "better". Please, other readers, be specially careful with this kind of posts, because this tips aren't good for anyone, usually.

Cheers!

Some comments have been hidden by the post's author - find out more