Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for ES6: Object destructing
Naftali Murgor
Naftali Murgor

Posted on

     

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 omittedconstresult={userId:'dummy_id_001`,  username:'foo_bar'  avatar:'https://gravatar/xrkpxys/k1szh.png',accent:'#fff'}// reading a few properties off this object literal: pre-es6varusername=result.usernamevaraccent=result.accent
Enter fullscreen modeExit fullscreen mode

In ES6, the above becomes:

// some code omittedconstresult={userId:'dummy_id_001`,  username:'foo_bar'  avatar:'https://gravatar/xrkpxys/k1szh.png',accent:'#fff'}// reading a few properties off this object literal: pre-es6let{username,accent,userId}=result// now use username, accent as normal variables
Enter fullscreen modeExit 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 ommittedconstusername=result.username// OK for single propertyconst{accent,avatar,userId}=result// use object destructing
Enter fullscreen modeExit fullscreen mode

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

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software developer and content creator. Author of the upcoming book, A Modern JavaScript Primer. Preorder a copy here https://naftalimurgor.gumroad.com/l/modern-javascript-primer
  • Location
    Nairobi, Kenya
  • Work
    Software Developer
  • Joined

More fromNaftali Murgor

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp