惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

人人都是产品经理
人人都是产品经理
D
Docker
GbyAI
GbyAI
B
Blog RSS Feed
博客园 - 司徒正美
博客园 - Franky
美团技术团队
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
aimingoo的专栏
aimingoo的专栏
C
Check Point Blog
IT之家
IT之家
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
www.infosecurity-magazine.com
www.infosecurity-magazine.com
AI
AI
O
OpenAI News
Attack and Defense Labs
Attack and Defense Labs
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Tailwind CSS Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
S
Secure Thoughts
博客园 - 聂微东
L
LINUX DO - 最新话题
U
Unit 42
SecWiki News
SecWiki News
A
Arctic Wolf
Schneier on Security
Schneier on Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
V
Visual Studio Blog
量子位
The Cloudflare Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
大猫的无限游戏
大猫的无限游戏
Google DeepMind News
Google DeepMind News
G
Google Developers Blog
T
Threat Research - Cisco Blogs
TaoSecurity Blog
TaoSecurity Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
B
Blog
博客园 - 【当耐特】
C
CERT Recently Published Vulnerability Notes
Scott Helme
Scott Helme
Last Week in AI
Last Week in AI
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Microsoft Security Blog
Microsoft Security Blog
Apple Machine Learning Research
Apple Machine Learning Research
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
A
About on SuperTechFans
博客园 - 三生石上(FineUI控件)
Latest news
Latest news

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback()
3 Ways To Access Object Properties in JavaScript
Dmitri Pavlutin · 2020-02-05 · via Dmitri Pavlutin Blog

You can access the properties of an object in JavaScript in 3 ways:

  1. Dot property accessor: object.property
  2. Square brackets property accessor: object['property']
  3. Object destructuring: const { property } = object

Let's see how each way works. And understand when it's reasonable, depending on the situation, to use one way or another.

Table of Contents

  • 1. Dot property accessor
    • 1.1 Dot property accessor requires identifiers
  • 2. Square brackets property accessor
  • 3. Object destructuring
    • 3.1 Alias variable
    • 3.2 Dynamic property name
  • 4. When the property doesn't exist
  • 5. Conclusion

1. Dot property accessor

A common way to access the property of an object is the dot property accessor syntax:

expression should evaluate to an object, and identifier is the name of the property you'd like to access.

For example, let's access the property name of the object hero:


const hero = {

name: 'Batman'

};

// Dot property accessor

console.log(hero.name); // => 'Batman'


Open the demo.

hero.name is a dot property accessor that reads the property name of the object hero.

You can use the dot property accessor in a chain to access deeper properties: object.prop1.prop2.

Choose the dot property accessor when the property name is known ahead of time.

1.1 Dot property accessor requires identifiers

The dot property accessor works correctly when the property name is a valid identifier. An identifier in JavaScript contains Unicode letters, $, _, and digits 0..9, but cannot start with a digit.

This is not a problem, because usually, the property names are valid identifiers: e.g. name, address, street, createdBy.

But sometimes properties are not valid identifiers:


const weirdObject = {

'prop-3': 'three',

'3': 'three'

};

weirdObject.prop-3; // => NaN

weirdObject.3; // throws SyntaxError: Unexpected number


Open the demo.

Because prop-3 and 3 are invalid identifiers, the dot property accessor doesn't work:

  • weirdObject.prop-3 evaluates to NaN, instead of the expected 'tree'
  • weirdObject.3 throws a SyntaxError!

Why does the expression weirdObject.prop-3 evaluate to NaN? Please write your answer below!

To access the properties with these special names, use the square brackets property accessor (which is described in the next section):


const weirdObject = {

'prop-3': 'three',

'3': 'three'

};

console.log(weirdObject['prop-3']); // => 'three'

console.log(weirdObject['3']); // => 'three'


Open the demo.

The square brackets syntax accesses without problems the properties that have special names: weirdObject['prop-3'] and weirdObject['3'].

2. Square brackets property accessor

The square brackets property accessor has the following syntax:

The first expression should evaluate to an object and the second expression should evaluate to a string denoting the property name.

Here's an example:


const property = 'name';

const hero = {

name: 'Batman'

};

// Square brackets property accessor:

console.log(hero['name']); // => 'Batman'

console.log(hero[property]); // => 'Batman'


Open the demo.

hero['name'] and hero[property] both read the property name by using the square brackets syntax.

Choose the square brackets property accessor when the property name is dynamic, i.e. determined at runtime.

3. Object destructuring

The basic object destructuring syntax is pretty simple:


const { identifier } = expression;


identifier is the name of the property to access and expression should evaluate to an object. After the destructuring, the variable identifier contains the property value.

Here's an example:


const hero = {

name: 'Batman'

};

// Object destructuring:

const { name } = hero;

console.log(name); // => 'Batman'


Open the demo.

const { name } = hero is an object destructuring. The destructuring defines a variable name with the value of property name.

When you get used to object destructuring, you will find that its syntax is a great way to extract the properties into variables.

Choose the object destructuring when you'd like to create a variable having the property value.

Note that you can extract as many properties as you'd like:


const { identifier1, identifier2, identifierN } = expression;


3.1 Alias variable

If you'd like to access the property, but create a variable with a name different than the property name, you could use aliasing.


const { identifier: aliasIdentifier } = expression;


identifier is the name of the property to access, aliasIdentifier is the variable name, and expression should evaluate to an object. After the destructuring, the variable aliasIdentifier contains identifier property value.

Here's an example:


const hero = {

name: 'Batman'

};

// Object destructuring:

const { name: heroName } = hero;

console.log(heroName); // => 'Batman'


Open the demo.

const { name: heroName } = hero is an object destructuring. The destucturing defines a new variable heroName (instead of name, as in the previous example), and assigns to heroName the value hero.name.

3.2 Dynamic property name

What makes the object destructuring even more useful is extracting dynamic name properties into variables:


const { [expression]: identifier } = expression;


The first expression should evaluate to a property name, and the identifier should indicate the variable name created after the destructuring. expression should evaluate to the object you'd like to destructure.

Here's an example:


const property = 'name';

const hero = {

name: 'Batman'

};

// Object destructuring:

const { [property]: name } = hero;

console.log(name); // => 'Batman'


Open the demo.

const { [property]: name } = hero is an object destructuring that dynamically, at runtime, determines what property to extract.

4. When the property doesn't exist

If the accessed property doesn't exist, all 3 accessor syntaxes evalute to undefined:


const hero = {

characterName: 'Batman'

};

console.log(hero.name); // => undefined

console.log(hero['name']); // => undefined

const { name } = hero;

console.log(name); // => undefined


Open the demo.

The property name doesn't exist in the object hero. Thus the dot property accessor hero.name, square brackets property accessor hero['name'] and the variable name after destructuring evaluate to undefined.

5. Conclusion

JavaScript provides a bunch of good ways to access object properties.

The dot property accessor syntax object.property works nicely when you know the variable ahead of time.

When the property name is dynamic or is not a valid identifier, a better alternative is square brackets property accessor: object[propertyName].

The object destructuring extracts the property directly into a variable: const { property } = object. Moreover, you can extract the dynamic property names (determined at runtime): const { [propertName]: variable } = object.

There are no good or bad ways to access properties. Choose depending on your particular situation and personal preferences.