DEV Community

Cover image for ES6: Object destructing
Naftali Murgor
Naftali Murgor

Posted on

2 1

ES6: Object destructing

Introduction

In this blog article, we shall learn about Object destructing in JavaScript. Object destructuring syntax was introduced in ES6 to make accessing Object properties much easier and cleaner

Object destructing

In pre-ES6, normally you'd read object properties and store the values associated to these properties in a variable like this:

// some code omitted
const result = {
  userId: 'dummy_id_001`,
  username: 'foo_bar'
  avatar: 'https://gravatar/xrkpxys/k1szh.png',
  accent: '#fff'
}

// reading a few properties off this object literal: pre-es6
var username = result.username
var accent = result.accent
Enter fullscreen mode Exit fullscreen mode

In ES6, the above becomes:

// some code omitted
const result = {
  userId: 'dummy_id_001`,
  username: 'foo_bar'
  avatar: 'https://gravatar/xrkpxys/k1szh.png',
  accent: '#fff'
}

// reading a few properties off this object literal: pre-es6
let {username, accent, userId} = result
// now use username, accent as normal variables
Enter fullscreen mode Exit fullscreen mode

This is useful especially if you need to read more than one property from the same object.

Summary

Object destructuring syntax provides a cleaner way of accessing more than one property off an object literal.

Use object destructuring when accessing more than one property of an object and pre-ES6 syntax(using the "dot" operator) when accessing only one object.

// possible code ommitted
const username = result.username // OK for single property
const {accent, avatar, userId} = result // use object destructing
Enter fullscreen mode Exit fullscreen mode

Found this article helpful? You may follow my twitter handle @nkmurgor where I tweet about interesting topics on web development.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay