November Black Friday Python week
This week up to 80% off on Python courses. More info
Black friday is here! Get up to 80 % extra points for free! More info

Lesson 10 - Object Properties in JavaScript

In the previous lesson, Inheritance And Polymorphism In JavaScript, we learned to use new OOP techniques - inheritance and polymorphism. Today, we're going to extend our knowledge of object properties and learn to add, print, and delete them. Before we start with that, let's repeat quickly how we can create object properties.

Adding properties

Objects in JavaScript are dynamic, so we can add and delete their properties even the objects have been already created. The most common syntax for adding a property is as follows: we write the object name and assign a new property to it using the dot operator:

const human = {
    name: 'John',
    age: 45
}

human.occupation = 'firefighter';

But there's another way to add an object property, which is through brackets []. We add square brackets after the object name and enter the property name as text. We can use this option, for example, when we don't know the property name yet and we'll get it from some variable later. Let's use the object from the previous example and add the same property to it, this time using brackets:

human['occupation'] = 'firefighter';
// or
const propertyName = 'occupation';
human[propertyName] = 'firefighter';

Iterating through object properties

Sometimes it happens that we need, for example, to print properties of our object. There are more ways to do this, let's show the most popular ones.

The for..in loop

The for..in loop works on almost the same principle as the standard for loop, but instead of declaring a control variable and setting the bounds, we just declare a variable that will contain the object property in each loop iteration. There will be as many iterations as the are properties of the object. Let's take a look at it:

const rectangle = {
    x: 10,
    y: 20,
    draw: function() {
        console.log('drawn');
    }
}

for (let index in rectangle) {
    console.log(index);
}

We have an object with the name rectangle, its properties are x, y, and it has a draw() method (ignore that the function only writes text to the console now). Once the loop finishes, the console that we open in our browser by pressing F12 would look like this:

x
y
draw

The property name has always been stored in each index and printed. To print the property values as well, the loop would look like this:

for (let index in rectangle) {
    console.log(index, rectangle[index]);
}

We use the above mentioned approach to access properties using square brackets. The loop works as follows:

  • the first property is stored to the index variable, in our case it's "x" (as string)
  • now we get to the second part of the log, where the property value is printed using square brackets, into which index is written. The index variable contains a string, so we'll get the value of that object property
  • this is how the loop repeats for all the properties

The result:

x 10
y 20
draw f () {
    console.log('drawn')
}

The keys() method

We can also use the keys() method to print object properties, which we call on the global Object class. Then, in parentheses, we write the object that we want to iterate through. Then we save it all to a variable, which we'll then print to the console. The big difference against the for..in loop is that the properties as returned as an array:

const rectangle = {
    x: 10,
    y: 20,
    draw: function() {
        console.log('drawn');
    }
}

const keys = Object.keys(rectangle);
console.log(keys);

and the result:

(3) ["x", "y", "draw"]
0: "x"
1: "y"
2: "draw"

The entries() method is another option which works on a similar principle.

Asking Whether an Object Has a Property

Sometimes it's a good idea to make sure that an object really has a property. For this purpose, we can use a standard condition and the in operator. Let's take a look at the rectangle from the previous example:

const rectangle = {
    x: 10,
    y: 20,
    draw: function() {
        console.log('drawn');
    }
}

if ('x' in rectangle) {
    console.log('Property exists!');
}

If our object has the x property, a message will be written to the console.

Deleting properties

We can also delete object properties. It's very simple, we use the delete keyword and the object name with the property we want to delete:

const rectangle = {
    x: 10,
    y: 20,
    draw: function() {
        console.log('drawn');
    }
}

delete rectangle.x;

If we now print the rectangle to the console, we'll see that it no longer has the x property:

rectangle
{y: 20, draw: f}

In the next lesson, Object Properties in JavaScript - Data Descriptors, we'll continue with object properties and introduce property descriptors.


 

 

Activities (2)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!