DEV Community

Mike Turck
Mike Turck

Posted on • Edited on

Quick Guide to Destructuring in ES6

Basic Destructuring

Destructuring is a feature of ES6 that lets you extract variables from larger json objects

const viewState = {
  latitude: -122.4,
  longitude: 37.78,
  zoom: 12
}

// Grab latitude and longitude from the viewState json object
const { latitude, longitude } = viewState;

console.log(latitude)  // -122.4
console.log(longitude) // 37.78
Enter fullscreen mode Exit fullscreen mode

Destructure and rename

// Grab latitude and longitude. 
// Rename them to lat and long, respectively
const { latitude:lat, longitude:long } = viewState;

console.log(lat)       // -122.4
console.log(lon)       // 37.78
Enter fullscreen mode Exit fullscreen mode

Destructure props passed to a React component

// sample props
{
    title: 'My Article Title',
    subTitle: 'A story of Destructuring'
}

// Without destructuring
const SimpleTitle = (props) => <h1>{props.title}</h1>

// With destructuring
const SimpleTitle = ({title}) => <h1>{title}</h1>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)