Lesson 20 of 34 · Objects
JavaScript Objects: Properties, Methods and this
Arrays are great for lists, but most real-world data has named parts: a hero has a name, a level, hit points and an inventory. In JavaScript, you group named values together in an object.
Objects are everywhere in JavaScript, from JSON data and configuration to DOM elements and API responses. In this lesson you'll create objects, read and change their properties, and give them behaviour with methods and this.
Object literals
An object literal is a list of key: value pairs inside curly braces. Each pair is a property:
const hero = {
name: "Ada",
level: 7,
isOnline: true,
inventory: ["sword", "map"],
};
Values can be anything, including arrays and other objects.
Reading properties: dot and bracket notation
Use dot notation when you know the property name while writing the code:
console.log(hero.name); // Ada
console.log(hero.level); // 7
console.log(hero.mana); // undefined (missing properties are undefined)
Use bracket notation when the name is stored in a variable, or isn't a valid identifier:
const stat = "level";
console.log(hero[stat]); // 7 (same as hero.level)
const records = { "high score": 9001 };
console.log(records["high score"]); // 9001 (keys with spaces need brackets)
A classic mistake is writing hero.stat when you mean hero[stat]. The first looks for a property literally called "stat".
Missing values: ?? and ?.
Two operators make missing properties easy to handle. a ?? b returns b only when a is null or undefined, so it's perfect for fallbacks. ?. (optional chaining) stops and returns undefined instead of crashing when the value on its left is null or undefined:
console.log(hero.mana ?? 0); // 0: mana is missing, so the fallback is used
console.log(hero.level ?? 0); // 7
console.log(hero.pet?.name); // undefined (hero.pet.name would throw a TypeError)
Prefer ?? over || for fallbacks: 0 || 10 is 10, because || replaces every falsy value, while 0 ?? 10 keeps the 0.
Adding, changing and deleting properties
You can change an object at any time, even one declared with const:
hero.level = 8; // update
hero.guild = "Coders"; // add a new property
delete hero.isOnline; // remove a property
console.log("guild" in hero); // true: the in operator checks for a key
Shorthand properties
When a variable has the same name as the property you want, you can write it once:
const name = "Linus";
const level = 3;
const player = { name, level }; // same as { name: name, level: level }
Methods
A function stored in an object is called a method. The shorthand method syntax is the most common way to write one:
const dragon = {
name: "Vexgold",
roar() {
return "ROOOAR!";
},
};
console.log(dragon.roar()); // ROOOAR!
this: the object before the dot
Inside a method, the keyword this refers to the object the method was called on, the one before the dot:
const counter = {
count: 0,
increment() {
this.count++;
return this.count;
},
};
counter.increment();
console.log(counter.increment()); // 2
this lets one method work with the data of whichever object it belongs to. Two important rules:
thisis decided by how the function is called, not where it's written. If you copy the method into a variable (const inc = counter.increment; inc();), the call has no object before the dot, sothisisn'tcounteranymore and the method breaks.- Arrow functions don't have their own
this. Don't use them for methods that needthis; use the shorthand method syntax instead.
Objects are references
A variable doesn't hold the object itself, only a reference to it. Assigning an object to another variable doesn't copy it:
const a = { hp: 10 };
const b = a;
b.hp = 0;
console.log(a.hp); // 0: a and b are the same object
For the same reason, { hp: 10 } === { hp: 10 } is false: they're two different objects.
Common mistakes
- Dot notation with a variable:
obj.keyinstead ofobj[key]. - Arrow functions as methods:
thiswill not point to your object. - Forgetting
this.inside a method:hp -= amountlooks for a variable calledhp, not the property.
Assignment
- Complete
createHero(name, hp). It returns a hero object with:- properties
name,hpandmaxHp. BothhpandmaxHpstart at thehpargument, which defaults to100. - a method
takeDamage(amount)that lowershpbyamount, never below0, and returns the newhp. - a method
heal(amount)that raiseshpbyamount, never abovemaxHp, and returns the newhp. - a method
isAlive()that returnstruewhilehpis greater than0.
- properties
- Write
getStat(hero, statName), which returns the value of the property namedstatName, or0if the hero doesn't have that property.
const hero = createHero("Ada");
hero.takeDamage(30); // 70
hero.heal(50); // 100 (capped at maxHp)
getStat(hero, "maxHp"); // 100
getStat(hero, "mana"); // 0Premium lesson
Unlock the full Learn JavaScript course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Keep learning
Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.
Lesson last updated on .