DEV Community

🦸‍♂️ 11 JavaScript Tips and Tricks to Code Like A Superhero (Vol.2)

Orkhan Jafarov on January 18, 2021

Hi JS-heroes! Finally done with this new article! Let's go ahead ✨ 1. Generate a list with random numbers We need A LOT of fake data, f...
Collapse
 
crimsonmed profile image
Médéric Burlet •

One that I love is this:

const someVar = null
const myValue = someVar || "default text"
Enter fullscreen mode Exit fullscreen mode

The or operator works the same as an elvis operator.

This is useful if you want to display a default value when you can't get data from an api or if some data is null for a key.

This can be chained with objects

const someVar = {foo: {bar: null}}
const myValue = someVar?.foo?.bar || "default text"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
lesleyvdp profile image
Lesley van der Pol • • Edited

Love this one too, it's also useful to prevent errors when destructuring something that could be undefined:

const { foo, bar } = couldBeUndefined || {};
Enter fullscreen mode Exit fullscreen mode

This can prevent errors such as "Cannot read foo of undefined".

Collapse
 
lampe profile image
Micha •

With ES2021 we have ||= :)
Which makes the syntax even cooler

I made a video about new features here:
youtu.be/hxmFYToenxE

Collapse
 
crimsonmed profile image
Médéric Burlet •

True but not fully supported yet

Thread Thread
 
lampe profile image
Micha •

With the right babelJS version it is ;)

Thread Thread
 
crimsonmed profile image
Médéric Burlet •

And then you're bringing big pieces of extra code for not much 😉 good way to slow websites.

Collapse
 
andrewcourtice profile image
Andrew Courtice •

Great article!

It's worth noting that the first 2 examples can be written ever so slightly shorter using Array.from as the Array.from method supports a mapping function as it's second argument.

Here's the first example using Array.from:

Array.from({ length: 1000 }, Math.random)
Enter fullscreen mode Exit fullscreen mode

And the second example:

Array.from({ length: 1000 }, (v, i) => i)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
orkhanjafarovr profile image
Orkhan Jafarov •

You're right! This way is slightly shorter! I'll replace mine with them
Thank you mate!

Collapse
 
ogheneovo12 profile image
ogheneovo12 •

Here is what I use

[...Array(1000).keys()]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
crimsonmed profile image
Médéric Burlet •
Collapse
 
renzos profile image
Renzo •

In the case of no. 5: I would always chose readability over bitwise trickery, when not absolutely necessary. So instead of bitwise AND, just use modulo;

const value = 232;  

if (value % 2) console.log("odd");
else console.log("even");
// even
Enter fullscreen mode Exit fullscreen mode
Collapse
 
chadgauth profile image
Chad Gauthier •

Hey just a small improvement to N something ago example to show/hide plural.

const fromAgo = (date) => {
  const ms = Date.now() - date.getTime();
  const seconds = Math.round(ms / 1000);
  const minutes = Math.round(ms / 60000);
  const hours = Math.round(ms / 3600000);
  const days = Math.round(ms / 86400000);
  const months = Math.round(ms / 2592000000);
  const years = Math.round(ms / 31104000000);
  let ago;

  if(seconds < 60)
    ago = `${seconds} second"`;
  else if (minutes < 60)
    ago = `${minutes} minute`;
  else if (hours < 24)
    ago = `${hours} hour`;
  else if (days < 30)
    ago = `${days} day`;
  else if (months < 12)
    ago = `${months} month`;
  else
    ago = `${years} year`;

  const isSingular = ago.indexOf("1 ") === 0;

  ago += isSingular ? " ago" : "s ago";
  return ago;
}

const createdAt = new Date(2021, 0, 5);
fromAgo(createdAt); // 14 days ago
Enter fullscreen mode Exit fullscreen mode
Collapse
 
fvlasenko profile image
Fedor Vlasenko •
const generatePathQuery = (path, obj) =>`${path}?${new URLSearchParams(obj).toString()}`;
const link = generatePathQuery("/user", { name: "Orkhan", age: 30 });
console.log(link);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
reflexgravity profile image
Joel D Souza •
case days < 30:
      return `${days} day(s) ago`;

Enter fullscreen mode Exit fullscreen mode

This will not work for months with 31 days.

Collapse
 
orkhanjafarovr profile image
Orkhan Jafarov • • Edited

It's a just simple version for that formatter. That's why it shows average time.
But it's okay with 31 days. If it's more than 30 days then 1 month;

example

new Date(2021, 0, 31); // now - 2021-01-30T20:00:00.000Z
const createdAt = new Date(2021, 0, 1); // 2020-12-31T20:00:00.000Z
fromAgo(createdAt); // 1 month(s) ago
Enter fullscreen mode Exit fullscreen mode

You can also replace Date.now() with your own date to check with date.getTime()

Collapse
 
larsolt profile image
Lars •

Array.from() is amazing! I always used new Array(10). Thanks :)

Collapse
 
mantiq profile image
A.Z. •

Great article :D

Collapse
 
aligulmaliyev profile image
Ali Gulmaliyev •

Thanks for your work.