본문 바로가기
TIL: Today I Learned

[TIL] 20201201 JavaScript Object Literals

by 김알리 2020. 12. 1.

Objects

  • Collections of properties
  • Property is a key-value pair
  • Rather than accessing data using an index, we use custom keys.

 

 

Creating Object Literals

  • Syntax
    • const obj = {key : value}
  • Example
const human = {
    firstName : 'Jiwan',
    lastName : 'Kim'
}

 

 

Accessing Data Out of Objects

  • Syntax
    • obj["key"]
    • obj.key
    • Examples
      • human["firstName"] //Jiwan
      • human.lastName //Kim
  • Keys
    • All keys are converted to strings, except for symbols.
    • obj[variableName] is also possible.
    • Example
const years = {1995: 'pig', 1997: 'cow'}
let birthYear = 1995;

years.birthYear  //undefined
years[birthYear]  //'pig'
years["birthYear"]  //undefined

 

 

Modifying Objects

  • Using const with objects
    • Just like arrays, using const, the reference of the object stays the same. Hence, using const instead of let is safer.
  • Modifying objects
    • Access to the property using key, and define the value. (Do the same when assigning a new property)
    • Example
const grades = {rob='A', dani='A+', emily='B'}
grades.emily = 'B+'; //modified
grades.hannah = 'A-'; //added

 

 

Nesting Arrays & Objects

  • Arrays + Objects
    • It's possible to nest arrays and objects. Very Useful in real life.

 

 

 

 

* This post is a summary of Udemy Course "The Web Developer Bootcamp" by Colt Steele.