Start learning free

LESSON 282 OF 671 · FUNCTIONS & CLASSES

Object Properties in JavaScript

Lesson

TL ; DR:

  • A property is a piece of data attached to an object. In JavaScript you don't declare them in the class — you just assign them with the dot operator:

    let dog = new Dog();
    dog.name = "Rex";
    dog.age = 4;
    

  • Each object has its own properties, so two dogs can have different names without interfering.



Full lesson:

Right now your Dog class is just an empty shell — every Dog object you create is identical. We need a way to attach data to each object.

In JavaScript, the data attached to an object is called a property. (Other languages call them fields or attributes — same idea.)


Setting properties

JavaScript is a dynamic language: you don't have to declare a property up front. Just assign to it with the dot operator:

let dog = new Dog();
dog.name = "Rex";
dog.age = 4;

After this, dog has a name property equal to "Rex" and an age property equal to 4.


Reading properties

console.log(dog.name);   // Rex
console.log(dog.age);    // 4

You read properties the same way you set them — with the dot operator.


Each object has its own properties

let rex = new Dog();
let luna = new Dog();
rex.name = "Rex";
luna.name = "Luna";
// rex.name is "Rex", luna.name is "Luna" — they don't interfere.

Your task

The Dog class is already defined for you. Below it, set dog.name to "Rex" and dog.age to 4. The pre-filled console.log will then show:

Rex is 4 years old
STEP 1 OF 1
    Ctrl + Enter to check