Зміст курсу
JavaScript Data Structures
JavaScript Data Structures
Working with Properties
Let's examine three important concepts related to working with object properties:
- Modifying property values;
- Adding new properties;
- Using shorthand properties.
Modifying Property Values
After creating an object, you can easily change the values of its properties. To do this, we simply refer to the property by name, using dot notation, and assign a new value.
Let's consider an example with a company object:
const company = { title: "Toyota", nativeName: "トヨタ自動車株式会社", industry: "Pharmacy", founded: { year: 1996, month: "August", day: 28, }, }; company.industry = "Automotive"; company.founded.year = 1937; console.log(company.industry); // Output: Automotive console.log(company.founded.year); // Output: 1937
In this example, we change the values of the industry
and founded.year
properties.
Adding New Properties
Adding a new property to an object is no different from changing the value of an existing property. If a property with a specified name doesn't already exist in the object, it will be created.
Consider the company object from the previous example:
const company = { title: "Toyota", nativeName: "トヨタ自動車株式会社", industry: "Automotive", founded: { year: 1937, month: "August", day: 28, }, }; company.founder = "Kiichiro Toyoda"; console.log(company.founder); // Output: Kiichiro Toyoda
In this example, we add the new property founder
to the company
object.
Using Shorthand Properties
Shorthand properties simplify the process of creating objects, especially when you want to use variable or function parameter values as property values.
This syntax allows us to use the variable name as the property name and its value as the property value.
Consider the following example:
const name = "Carl Benz"; const birthCountry = "Germany"; const person = { name: name, birthCountry: birthCountry, }; console.log(person.name); // Output: Carl Benz console.log(person.birthCountry); // Output: Germany
Using shorthand properties, the same object can be created more succinctly:
const name = "Carl Benz"; const birthCountry = "Germany"; const person = { name, birthCountry, }; console.log(person.name); // Output: Carl Benz console.log(person.birthCountry); // Output: Germany
With shorthand properties, we only need to specify the property name, and the value is automatically taken from a variable with the same name.
Дякуємо за ваш відгук!