DEV Community

Daniel Trejo
Daniel Trejo

Posted on

Exploring Destructuring in JS

Hello, my name is Daniel and I'm a beginner at coding. I am an active student at Flatiron School. In phase-2 we delve heavily into react and all the amazing things it can do. Today I decided to talk about Destructuring a little because it is a super simple yet amazing piece of code. Destructuring allows for a more concise and cleaner code. If I were to have code like this;

function EmojiButton(props) {
  return (
    <button>
      <span role="img">{props.emoji}</span>
      {props.label}
    </button>
  )
}
Enter fullscreen mode Exit fullscreen mode

If you take a look at the code block, you will see that in some brackets there are some react components that lets us access that information we are grabbing from the props.emoji and the props.label. Destructuring can be used to clean up some of the the unnecessary words. We can do this a couple ways. One way to do it is doing a const and assigning them as variable that equal the word "props". That will allow us to go without the word props within the components.

function EmojiButton(props) {
const { emoji, label } = props
  return (
    <button>
      <span role="img">{emoji}</span>
      {label}
    </button>
  )
}
Enter fullscreen mode Exit fullscreen mode

As you can see, it looks a little nicer not having the props all over the place. Now I know it doesn't look like it's doing to much here but I promise when you start coding bigger and longer projects. It will start looking all over the place. Props will be literally everywhere. This way you can see exactly what is it's talking about in a specific piece of code instead of looking through "props" over and over again.

Now, I prefer a different way of desctructuring and it looks like this;

function EmojiButton({emoji, label}) {
  return (
    <button>
      <span role="img">{emoji}</span>
      {label}
    </button>
  )
}
Enter fullscreen mode Exit fullscreen mode

It does the same thing as the code block before however I really like the fact that it is integrated into the function itself instead of creating a const variable. It looks a lot nicer and cleaner. Now there will be use cases for both and obviously go with whichever one you feel more comfortable with. A lot of coding is preferences with how you want to go about it. Anyway, destructuring is super useful later one when you coding more than a few lines.

Top comments (0)