DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

Cover image for TIPS & TRICKS OF JAVASCRIPT & REACT
Nipu Chakraborty
Nipu Chakraborty

Posted on

TIPS & TRICKS OF JAVASCRIPT & REACT

TIPS 1: Easiest way of string to integer conversion.

const value_1 = "1" 

const value_2 = "2"

function add(field_1, field_2){

  return field_1 + field_2;
}


add(+value_1, +value_2); 
Enter fullscreen mode Exit fullscreen mode

TIPS 2: Easiest way of float to integer conversion.

const floatToInt = 23.9 | 0;
Enter fullscreen mode Exit fullscreen mode

TIPS 3: Use Global object always should not need localStorage

Note[if data is is static then you should use it. and donโ€™t use any kind secret or confidential data here..]

const user = {

  first_name: "Rowan",

  last_name: "Atkinson"
}

window.user=user
Enter fullscreen mode Exit fullscreen mode

TIPS 3: Donโ€™t use if not necessary ternary (?:)

const DemoComponent = ()=>{

const [show, setShow] = useState(false)

   return (<div>

     {show? <Message/>: ''}

</div>)
}
Enter fullscreen mode Exit fullscreen mode

Right way with (&&)

const DemoComponent = ()=>{
const [show, setShow] = useState(false)

   return (<div>
     {show && <Message/>}
    </div>)
}
Enter fullscreen mode Exit fullscreen mode

TIPS 4: Donโ€™t do it

if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
     let variable2 = variable1;
}
Enter fullscreen mode Exit fullscreen mode

Do this short and simple

const variable2 = variable1  || 'new';
Enter fullscreen mode Exit fullscreen mode

TIPS 5: Donโ€™t do it

Math.floor(4.9) === 4 // true
Enter fullscreen mode Exit fullscreen mode

Do this short and simple

~~4.9 === 4 // true
Enter fullscreen mode Exit fullscreen mode

TIPS 6: Donโ€™t do it

switch (something) {

  case 1:
    doSomething();

  break;
case 2:
    doSomethingElse();
  break;
case 3:
    doSomethingElseAndOver();
  break;
  // And so on...
}
Enter fullscreen mode Exit fullscreen mode

Do this short and simple

const cases = {
  1: doSomething(),

  2: doSomethingElse(),

  3: doSomethingElseAndOver()
};
Enter fullscreen mode Exit fullscreen mode

[Note: This one has performance issue I prefer use this one when you have crying need. Switch statement is more faster than this solution

TIPS 7: Donโ€™t do it

if(x == 1 || x == 5 || x == 7)  {
  console.log('X has some value');
}
Enter fullscreen mode Exit fullscreen mode

Do this short and simple

([1,5,7].indexOf(x) !=- 1) && console.log('X has some value!');
Enter fullscreen mode Exit fullscreen mode

TIPS 8: Don't do it

const param1 =1;
const param2 = 2;
const param3 = 3;
const param4 = 4;


function MyFunc =(param1, param2, param3, param4)=>{
  console.log(param1, param2, param3, param4)
}

MyFunc(param1, param2, param3, param4)

Enter fullscreen mode Exit fullscreen mode

Do this short and simple

const params = {param1: 1, param2: 2, param3: 3, param4: 4}

function MyFunc =({param1, param2, param3, param4})=>{
  console.log(param1, param2, param3, param4)

}

MyFunc(params)
Enter fullscreen mode Exit fullscreen mode

TIPS 9: Donโ€™t do it

function Myfunc(value){
   if(value){
     console.log("you have a value")
   }else{
      throw new Error("You don't have a value")
   }
}
Enter fullscreen mode Exit fullscreen mode

Do this short and simple

NOTE: If you check error first then itโ€™s donโ€™t go else block but if you do first one it will check first value is exist then if not found it will go the else block.

function Myfunc(value){
   return !value ? throw new Error("You don't have a value") : console.log("you have a value")
}
Enter fullscreen mode Exit fullscreen mode

Top comments (12)

Collapse
 
lukeshiru profile image
Info Comment hidden by post author - thread only accessible via permalink
Luke Shiru • Edited on

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!

Collapse
 
miketalbot profile image
Mike Talbot • Edited on

Nice list :)

I'd just say on Tip 7: [1,5,7].includes(x) is neater as there's no magic -1 (and it's shorter)

Tip 8: can work, but functions with few parameters can benefit from not having to force names on the user.

Collapse
 
nipu profile image
Nipu Chakraborty Author

Thanks for your feedback

Collapse
 
val_baca profile image
Valentin Baca

For Tip #5, the ~~ trick is more like Math.trunc rather than Math.floor

See the behavior on negative numbers:

Math.floor(-2.2)
-3
Math.trunc(-2.2)
-2
~~(-2.2)
-2
Enter fullscreen mode Exit fullscreen mode
Collapse
 
itays123 profile image
Itay Schechner

This is some useful piece of content

Collapse
 
nipu profile image
Nipu Chakraborty Author

Thanks

Collapse
 
prabhukadode profile image
Prabhu

Nice

Collapse
 
abhighyaa profile image
Abhighyaa Jain

Hey, how does logical or(|) turns a floating no to integer?

Collapse
 
lukeshiru profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
Luke Shiru • Edited on

This list of tips is actually harmful. I wrote a detailed comment and the author hid it instead of addressing it, so he's aware of the issues with the list of tips and prefers to hide my comment (and probably others) highlighting the issues with it.

Edit: Due to the fact that it seems he reported this comment as well, and dev.to favor him instead of me by marking it as "low quality comment" when this is actually a "low quality post" which is clearly not allowed in the content policy, I'll proceed to block the author so I no longer see his posts, but other readers please be aware of this kind of lists of tips and do your own research, because writing less is not always better.

Collapse
 
val_baca profile image
Valentin Baca

I agree with your detailed comment. There are more readable built-in functions for many of these tricks. Some of these tricks don't handle all the cases well (like using || for default breaks if zero is given and should be considered a valid input).

These are more "cute" tricks or "hacks" than ones you should be pulling into your production code.

Collapse
 
samueljklee profile image
Samuel Lee

I read your detailed comments and completely agree with the points mentioned.
I think the author should be open to the community's feedback. It's not even offensive but rather can help the author and the community to learn.

Collapse
 
olvnikon profile image
Vladimir

Totally agree with you. Had the same feelings when was reading those "tips". The comment is constructive and not offensive at all. I'm supporting you on the concern.

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

๐ŸŒš Turn on dark mode

๐Ÿ”  Change your default font

๐Ÿ“š Adjust your experience level to see more relevant content

ย 

Head to your account's Settings to do all this and more.