DEV Community

Esto Triramdani N
Esto Triramdani N

Posted on

Array Destructuring

Introduction

I really want to create a written programming tutorial, but I don't know where to start since programming is a big playground. Yes, I can start anywhere but this is also being my problem: I can't describe any and where. The idea is just spinning around in my head for months 🤕.
I finally decided to start by defined my goal: building MERN (MongoDB, Express.js, React.js, and Node.js) stack app. It made me easier to create tutorial structure later.

This tutorial covers the following lessons:

  1. JavaScript Refreshment for Building React App
  2. React.js as frontend library/framework
  3. Express.js as backend library/framework
  4. MongoDB as database to store our data
  5. Integrating Express.js and MongoDB

We will learn those things one by one. So this tutorial, we are not going to build a really MERN app. We only want to learn everything we need to build a MERN app. Later after we learn together in this tutorial, we are ready to build MERN app without any fundamental knowledge issues.

If you have any thoughts, feel free to catch me at

Array Destructuring

Desctruturing is an important concept we should know before starts building app with React.
For example, we create a function that returns an array.

const getRandomTwoNumbers = () => {
    const numbers = [Math.random(), Math.random()];
    return numbers;
};
Enter fullscreen mode Exit fullscreen mode

We can call this function and get each items like this:

const numbs = getRandomTwoNumbers();
const numberOne = numbs[0];
const numberTwo = numbs[1];
console.log(numberOne, numberTwo);
Enter fullscreen mode Exit fullscreen mode

But there is a short way to do that.

const [numberOne, numberTwo] = getRandomTwoNumbers();
console.log(numberOne, numberTwo);
Enter fullscreen mode Exit fullscreen mode

It is more simple, right?
You can treat numberOne and numberTwo as constant: you can name it anything you want.

So, let's do it in 👨🏻‍💻 React

You might have seen or familiar with this code snippet.

const [name, setName] = useState('Esto');
Enter fullscreen mode Exit fullscreen mode

We can also wrote code above like this.

const nameState = useState('Esto');
const name = nameState[0];
const setName = nameState[1];
Enter fullscreen mode Exit fullscreen mode

... because useState returns an array that has two lengths (it's guaranted by React).
Array destructuring syntax made our code simplier and it can save 2 lines.

Keep code 💻 and see you in the next post! 🍻

Top comments (0)