Access properties of javascript object

3 Ways To Access Object Properties in JavaScript

Post cover

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.

Before I go on, let me recommend something to you.

The path to becoming good at JavaScript isn’t easy. but fortunately with a good teacher you can shortcut.

Take «Modern JavaScript From The Beginning 2.0» course by Brad Traversy to become proficient in JavaScript in just a few weeks. Use the coupon code DMITRI and get your 20% discount!

Table of Contents

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 :

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:

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):

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.

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.

The basic object destructuring syntax is pretty simple:

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.

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:

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

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.

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 .

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

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.

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 :

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 .

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.

Источник

Property accessors

Property accessors provide access to an object’s properties by using the dot notation or the bracket notation.

Try it

Syntax

.propertyName object[expression] 

Description

One can think of an object as an associative array (a.k.a. map, dictionary, hash, lookup table). The keys in this array are the names of the object’s properties.

There are two ways to access properties: dot notation and bracket notation.

Dot notation

In the object.propertyName syntax, the propertyName must be a valid JavaScript identifier which can also be a reserved word. For example, object.$1 is valid, while object.1 is not.

const variable = object.propertyName; object.propertyName = value; 
const object = >; object.$1 = "foo"; console.log(object.$1); // 'foo' 
const object = >; object.1 = 'bar'; // SyntaxError console.log(object.1); // SyntaxError 

Here, the method named createElement is retrieved from document and is called.

If you use a method for a numeric literal, and the numeric literal has no exponent and no decimal point, you should leave white-space(s) before the dot preceding the method call, so that the dot is not interpreted as a decimal point.

77 .toExponential(); // or 77 .toExponential(); // or (77).toExponential(); // or 77..toExponential(); // or 77.0.toExponential(); // because 77. === 77.0, no ambiguity 

Bracket notation

In the object[expression] syntax, the expression should evaluate to a string or Symbol that represents the property’s name. So, it can be any string literal, for example, including ‘1foo’ , ‘!bar!’ , or even ‘ ‘ (a space).

const variable = object[propertyName]; object[propertyName] = value; 

This does the exact same thing as the previous example.

A space before bracket notation is allowed.

Passing expressions that evaluate to property name will do the same thing as directly passing the property name.

const key = "name"; const getKey = () => "name"; const Obj =  name: "Michel" >; Obj["name"]; // returns "Michel" Obj[key]; // evaluates to Obj["name"], and returns "Michel" Obj[getKey()]; // evaluates to Obj["name"], and returns "Michel" 

However, beware of using square brackets to access properties whose names are given by external input. This may make your code susceptible to object injection attacks.

Property names

Each property name is a string or a Symbol. Any other value, including a number, is coerced to a string. This outputs ‘value’ , since 1 is coerced into ‘1’ .

const object = >; object["1"] = "value"; console.log(object[1]); 

This also outputs ‘value’ , since both foo and bar are converted to the same string ( «[object Object]» ).

const foo =  uniqueProp: 1 >; const bar =  uniqueProp: 2 >; const object = >; object[foo] = "value"; console.log(object[bar]); 

Method binding

It’s typical when speaking of an object’s properties to make a distinction between properties and methods. However, the property/method distinction is little more than a convention. A method is a property that can be called (for example, if it has a reference to a Function instance as its value).

A method is not bound to the object that it is a property of. Specifically, this is not fixed in a method and does not necessarily refer to the object containing the method. Instead, this is «passed» by the function call. See the reference for this .

Examples

Bracket notation vs. eval()

JavaScript novices often make the mistake of using eval() where the bracket notation can be used instead.

For example, the following syntax is often seen in many scripts.

const x = eval(`document.forms.form_name.elements.$strFormControl>.value`); 

eval() is slow and should be avoided whenever possible. Also, strFormControl would have to hold an identifier, which is not required for names and id s of form controls. It is better to use bracket notation instead:

const x = document.forms.form_name.elements[strFormControl].value; 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 30, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

JavaScript Object Properties

Properties are the most important part of any JavaScript object.

JavaScript Properties

Properties are the values associated with a JavaScript object.

A JavaScript object is a collection of unordered properties.

Properties can usually be changed, added, and deleted, but some are read only.

Accessing JavaScript Properties

The syntax for accessing the property of an object is:

The expression must evaluate to a property name.

Example 1

Example 2

JavaScript for. in Loop

The JavaScript for. in statement loops through the properties of an object.

Syntax

The block of code inside of the for. in loop will be executed once for each property.

Looping through the properties of an object:

Example

const person = <
fname:» John»,
lname:» Doe»,
age: 25
>;

for (let x in person) txt += person[x];
>

Adding New Properties

You can add new properties to an existing object by simply giving it a value.

Assume that the person object already exists — you can then give it new properties:

Example

Deleting Properties

The delete keyword deletes a property from an object:

Example

const person = <
firstName: «John»,
lastName: «Doe»,
age: 50,
eyeColor: «blue»
>;

Example

const person = <
firstName: «John»,
lastName: «Doe»,
age: 50,
eyeColor: «blue»
>;

The delete keyword deletes both the value of the property and the property itself.

After deletion, the property cannot be used before it is added back again.

The delete operator is designed to be used on object properties. It has no effect on variables or functions.

The delete operator should not be used on predefined JavaScript object properties. It can crash your application.

Nested Objects

Values in an object can be another object:

Example

You can access nested objects using the dot notation or the bracket notation:

Example

Example

Example

Example

Nested Arrays and Objects

Values in objects can be arrays, and values in arrays can be objects:

Example

To access arrays inside arrays, use a for-in loop for each array:

Example

for (let i in myObj.cars) <
x += «

» + myObj.cars[i].name + «

«;
for (let j in myObj.cars[i].models) <
x += myObj.cars[i].models[j];
>
>

Property Attributes

All properties have a name. In addition they also have a value.

The value is one of the property’s attributes.

Other attributes are: enumerable, configurable, and writable.

These attributes define how the property can be accessed (is it readable?, is it writable?)

In JavaScript, all attributes can be read, but only the value attribute can be changed (and only if the property is writable).

( ECMAScript 5 has methods for both getting and setting all property attributes)

Prototype Properties

JavaScript objects inherit the properties of their prototype.

The delete keyword does not delete inherited properties, but if you delete a prototype property, it will affect all objects inherited from the prototype.

Источник

Читайте также:  Python print number digits
Оцените статью