"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Object Literals

Object Literals

Published on 2024-08-15
Browse:502

Object Literals

Objects are collections of key-value pairs (properties).

To create an object we can do as follows:

let person = {
   firstName: 'Megan',
   isOnVacation: true,
   favFoods: ['plum', 'salad', 'fritos']
}

To access values within the object we can:

console.log(person.isOnVacation); // true
console.log(person['isOnVacation']); // true

We can also make an object that contains objects:

let student = {
   name: 'Jimmy',
   exams: {
      artFinal: 'A',
      mathFinal: 88
   }
}

To access a value in the object's object, we can:

console.log(student.exams.artFinal); // 'A'

Also, we can make arrays containing objects:

let friends = [
   {
      name: 'Sorour',
      favColor: 'blue',
      metAt: 'college'
   },
   {
      name: 'Timothy',
      favColor: 'red',
      metAt: 'Starbucks'
   }
];

To access a value in the second object, we can call:

console.log(friends[1].favColor); // 'red'

To update a value in the second object, we can:

friends[1].name = 'Tim';

console.log(friends[1].name); // Tim
Release Statement This article is reproduced at: https://dev.to/meganpaffrath/object-literals-1d93?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3