JavaScript
Tutorial: objects in JavaScript - build a business card
Learn to create and use JavaScript objects by building a digital business card.
If an array is a list, an object is a profile card: a named set of data, like a business card. Let's build one.
Step 1: create your object
const person = {
name: 'Sofia',
age: 28,
job: 'Developer',
greet() {
return `Hi, I'm ${this.name}`;
},
};
Each key: value is a property. greet is a method: a function that lives inside the object. this.name means "this object's own name".
Step 2: access and update properties
console.log(person.name); // 'Sofia'
person.age = 29; // happy birthday, congrats
console.log(person.age); // 29
You can read and change properties with object.property. No permission needed, no forms to sign.
Step 3: call a method
console.log(person.greet()); // "Hi, I'm Sofia"
Step 4: loop through the object's properties
for (const key in person) {
if (typeof person[key] !== 'function') {
console.log(`${key}: ${person[key]}`);
}
}
for...in loops through every key on the object. The if avoids printing the greet method as if it were just another piece of data (nobody wants to see a function's source code on their business card).
What did you just learn?
- How to create an object with properties and methods.
- How to access and update properties with
object.property. - How to loop through an object's keys with
for...in.