Rename & Destructure Variables in ES6

Rename & Destructure Variables in ES6

Last post we took a look at an intro to destructuring. Let's take a look at another use case which would be renaming your variables. Sometimes data comes back in some odd names, and you might not necessarily want to use a property key as the end variable name. Maybe you don't like that variable name or it's already taken in your scope.

const twitter = 'twitter.com';
const wes = {
  first: 'Wes',
  last: 'Bos',
  links: {
    social: {
      twitter: 'https://twitter.com/wesbos',
      facebook: 'https://facebook.com/wesbos.developer',
    },
    web: {
      blog: 'https://wesbos.com'
    }
  }
};

For example here, I already used twitter as a variable. I can't use it again, but I'm stuck, because this object gives me twitter as a key. What you can do is you can rename them as you destructure them.

So - I want the twitter property, but I want to call it tweet. I want the facebook property, but I want to call it fb.

const { twitter: tweet, facebook: fb } = wes.links.social;

The above code will pull the wes.links.social.twitter into a variable called tweet and similarly fb for facebook.

Find an issue with this post? Think you could clarify, update or add something?

All my posts are available to edit on Github. Any fix, little or small, is appreciated!

Edit on Github

Syntax Podcast

Hold on — I'm grabbin' the last one.

Listen Now →
Syntax Podcast

@wesbos Instant Grams

Beginner JavaScript

Beginner JavaScript

A fun, exercise heavy approach to learning Modern JavaScript from scratch. This is a course for absolute beginners or anyone looking to brush up on their fundamentals. Start here if you are new to JS or programming in general!

BeginnerJavaScript.com
I post videos on and code on

Wes Bos © 1999 — 2024

Terms × Privacy Policy