AI Hints
JavaScript · Lesson 59 of 138

Accessing Properties

Dot and brackets.

⏱ 2 min read▶ Video at 1:12:08🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Each key and value in an object is called a property. There are two ways to read a property, with a dot, or with square brackets. And you can add, change, or delete properties at any time.

Accessing Properties
From the video: Accessing Properties
  • Key and value: a property
  • Dot or brackets
  • Add, change, delete

Reading and changing

Dot notation is the usual way. Bracket notation takes a string, so the key can come from a variable. Assigning to a property changes it, or adds it if it's new. Delete removes it. And reading a missing property gives undefined. Run it.

app.jsjavascript
const car = { brand: "Volvo", year: 2019 };

console.log(car.brand);
const key = "year";
console.log(car[key]);

car.year = 2021;
car.color = "blue";
delete car.brand;
console.log(car);
console.log(car.wheels);
Output
Volvo
2019
{ year: 2021, color: 'blue' }
undefined

Checking for a property

To check whether an object has a key, use the in operator, like, color in car. Or object dot has own. Be careful just checking if car dot color is truthy, because a value of zero or an empty string would look missing.

keyvalue
obj.keydot notation
obj["key"]brackets, any string
delete obj.keyremove
"key" in objdoes it exist?

Summary

Read properties with dots or brackets, assign to change or add them, and delete removes them. Next, functions inside objects, and this.

Key takeaways
  • obj.key / obj[key]
  • Assign to add or change
  • Missing gives undefined
Next up: Methods and this — functions inside objects