Codementor Events

Level Up Your Javascript - Part 1

Published Jun 17, 2022Last updated Jun 29, 2022
Level Up Your Javascript - Part 1

Hi Codementor!
I'm starting this series where in each article I will share bite-sized tidbits of Javascript coding awesomeness to make your repositories cleaner and nicer to look at. Enjoy!

Getting Rid of Empty Values in an Array

It's simple like this:

const array = [1, 2, null, '', 4, 6, 22];
const fullArray = array.filter((a) => a);

This will get rid of the null and '' elements.
But the (a) => a smells a bit. However, you can just do this:

const fullArray = array.filter(Boolean);

And it does the same thing!
Beware, 0 is a falsey value and would also be removed, sadly. Use this only if you know your data source won't give you these issues.

Array Destructuring Powers

If you don't know what Array Destructuring is, you actually do, especially if you use React Hooks, because it's built-in:

const [state, setState] = useState();

This is destructuring the return value of useState, which is an array with the first element being a variable and second a function. It's the shorthand version of saying:

const stateArray = useState();
const state = stateArray[0];
const setState = stateArray[1];

And you can see how much easier it is to code. It's also aesthetically more appealing in my opinion.
But let's take this power to the next level. Suppose you need to set a bunch of variables at the beginning of your scope,such as:

let principalValue = 0;
let term = 20;
let interestRate = 12.5;
let monthlyPayment = 5000;

And so on. Yes, you can shorthand it like this:

let principalValue = 0,
  term = 20,
  interestRate = 12.5,
  monthlyPayment = 5000;

But you can ALSO do this:

let [principalValue, term, interestRate, monthlyPayment] = [0, 20, 12.5, 5000];

Which I find to be a lot more concise, and it comes with some nifty features, such as if you need to transform each value in some way, you wouldn't have to do this:

let principalValue = transform(0),
  term = transform(20),
  interestRate = transform(12.5),
  monthlyPayment = transform(5000);

You can just do this:

let [principalValue, term, interestRate, monthlyPayment] = [
  0, 20, 12.5, 5000,
].map(transform);

and adding more variables doesn't bloat your code! What if you want a different transform function for each value? simple:

const transformMap = {
  0: transform,
  1: transform1,
  2: transform2,
  3: transform3,
};

let [principalValue, term, interestRate, monthlyPayment] = [
  0, 20, 12.5, 5000,
].map((value, index) => transformMap[index](value));

Here we leverage the index argument of the map method to hook the value to its correct transform function.

Object destructuring is just as powerful,especially if you're looking for nested values:

const {
  user: {
    firstName,
    lastName,
    mainInterest: {
      type,
      description,
      category: { name },
    },
  },
} = data;

Now each variable name, type, description, firstName, lastName is accessible. Sure beats:

const name = data.user.mainInterest.category.name;
const description = data.user.mainInterest.description;
// etc

In summary, I absolutely love the power of destructuring and want to share it with you!

Optimize Array Searches

So I use this all the time. Say I want to shape an array but I also want to get metadata from that array. One way of doing such is:

const shapedUsers = users.map((user) => shape(user));
const activeUserCount = shapedUsers.filter((user) => user.isActive).length;
const underageUserCount = shapedUsers.filter((user) => user.age < 18).length;
const userDetails = shapedUsers.reduce(
  (details, user) => [...details, user.details],
  [],
);
// etc

This is nice, but if I have 100 000 users, I'm mapping through the array 4 times and this might get very slow. A better way to do it (using array destructuring like we saw above!) is:

let [activeUserCount, underageUserCount, userDetails] = [0, 0, []];

const shapedUsers = users.map((user) => {
  activeUserCount += user.isActive ? 1 : 0;
  underageUserCount += user.age < 18 ? 1 : 0;
  userDetails.push(user.details);

  return shape(user);
});

I go through the array once and build up every variable I need. I can then easily add to my initial value array and customise according to my needs.

Summary

We learned some cool things when working with arrays. I hope you can implement these in your own code and really impress those you need to!

Until next time, happy coding!

~ Sean

Discover and read more posts from Sean Hurwitz
get started
post commentsBe the first to share your opinion
Thomas Theiner
2 years ago

Hi Sean,

thanks for those enlightening examples.

One remark: Under Array Destructuring Powers the last code example should be

const name = data.user.mainInterest.category.name;
const description = data.user.mainInterest.description;
// etc
Sean Hurwitz
2 years ago

You’re right, thank you! I’ll amend

Carlos Guevara
2 years ago

The last one, helped me a lot. Thank you

Sean Hurwitz
2 years ago

You’re welcome!

Show more replies