Generative Data Intelligence

Level Up Your Javascript – Part 1

Date:

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!

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.

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 = user.mainInterest.category.name;
const description = user.mainInterest.description;

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

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],
  [],
);

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.

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

spot_img

Latest Intelligence

spot_img

Chat with us

Hi there! How can I help you?