Object
An object is a collection of data composed of key-value pairs.
Here, keys are strings and values can be of various data types (primitives, objects, functions, etc.).
Creating an Object
In JavaScript, you can create an object using curly braces { }
.
You can represent your wallet as an object as shown below.
let wallet = {
money: 10000,
creditCard: 'Visa',
photo: 'family photo',
driver'sLicense: true,
};
Items like money
, creditCard
, photo
, and driver'sLicense
inside the object are called 'properties' or 'keys', and the values associated with these keys are called 'values'.
Accessing Information from an Object
-
Using the dot (
.
) notation: This is the most commonly used method.Accessing object information with dot notationlet myMoney = wallet.money; // 10000
-
Using brackets (
[]
) with the key: This method is useful when the key is given as a variable or contains spaces or special characters.Accessing object information with bracketslet card = 'creditCard';
let myCard = wallet[card]; // 'Visa'
Modifying and Adding Information to an Object
To modify or add information to an object, you can use either the dot (.
) notation or the bracket ([]
) notation.
// Adding new properties
wallet.height = 170;
wallet['creditCard'] = 'MasterCard';
// Modifying existing property values
wallet.money = 5000;
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.