JavaScript #18 ~ Object

HJ's Coding Journey·2021년 7월 16일
0

[Learn] JavaScript

목록 보기
19/20

An object is also a type of data structure used for storing various data. In arrays, we find our data by referencing a specific position number in which the data is stored. In the long-run, this method can be very time-consuming when we don't know where to find our data. In objects, however, we can give names to our data by creating properties. With properties, we can find our data through property names. This relationship between properties and data is known as the key-value pair.

// array
const personArray = [
    'John',
    'Smith',
    2037 - 1991,
    'teacher',
    ['Michael', 'Peter', 'Steven']
];
// --object (able to give names(key) to values)--
const person = { // for object, order doesn't matter)
    firstName: 'John',
    lastName: 'Smith',
    age: 2037 - 1991,
    job: 'teacher',
    friends: ['Michael', 'Peter', 'Steven']
};

In objects, we either use the dot notation or the bracket notation. The two methods have the same functionality of calling values within properties.

// dot notation
person.lastName // Smith
person["lastName"] // Smith

It is actually easier to use dot notations as they are more straight-forward. However, using bracket notations gives us more freedom and control over objects. With bracket notations, we can concatenate strings that have similar names and we could also call existing variables when we don't know which properties we are retrieving. In these cases, we omit the double apostrophe (" ") within the bracket.

Ex) object[property]

// Ex) (Retrieving properties by concatenating strings that have similar names)
const nameKey = "Name";
console.log(person["first" + nameKey]); // John
console.log(person["last" + nameKey]); // Smith
//--
// Ex) (When we don't know which property we are retrieving)
const interestedIn = prompt(
  "What do you want to know about John? Choose between firstName, lastName, age, job, and friends"
);
//--
if (person[interestedIn]) {
  console.log(person[interestedIn]);
} else {
  console.log(
    "Wrong request! Choose between firstName, lastName, age, job, and friends"
  );
}

We can also change existing values within object properties using either dot or bracket notation.

person.location = "United States";
person["twitter"] = "@johnsmith";
const person = {
    firstName: 'John',
    lastName: 'Smith',
    age: 2037 - 1991,
    job: 'teacher',
    friends: ['Michael', 'Peter', 'Steven']
  	location: 'United States',
  	twitter: '@johnsmith'
};
profile
Improving Everyday

0개의 댓글