DEV Community

Cover image for JavaScript Objects πŸ€” πŸ’»
Irena Popova πŸ‘©πŸ»β€πŸ’»
Irena Popova πŸ‘©πŸ»β€πŸ’»

Posted on • Updated on

JavaScript Objects πŸ€” πŸ’»

Objects in JavaScript are collections of key/value pairs. The values can consist of properties and methods, and may contain all other JavaScript data types, such as strings, numbers, and Booleans.

So roughly:

  • all objects in JavaScript are maps (dictionaries) from strings to values.
  • A (key, value) entry in an object is called a property.
  • The key of a property is always a text string.
  • The value of a property can be any JavaScript value, including a function.
  • Methods are properties whose values are functions.

All objects in JavaScript descend from the parent Object constructor. They have many useful built-in methods we can use and access to make working with individual objects straightforward.
There are three kinds of properties:

  • Properties (or named data properties) Normal properties in an objectβ€”that is, mappings from string keys to values. Named data properties include methods. This is by far the most common kind of property.
  • Accessors (Getters/Setters) (or named accessor properties) Special methods whose invocations look like reading or writing properties. Normal properties are storage locations for property values; accessors allow you to compute the values of properties. They are virtual properties.
  • Internal properties
    Exist only in the ECMAScript language specification. They are not directly accessible from JavaScript, but there might be indirect ways of accessing them. The specification writes the keys of internal properties in brackets. For example, [[Prototype]] holds the prototype of an object and is readable via Object.getPrototypeOf().

  • Object Literals
    JavaScript’s object literals allow you to directly create plain objects (direct instances of Object).

In the following code snippet an object literal is used to assign an object to the variable Irene. The object has the two properties: name and describe. describe is a method:

let irene = {
    name: 'Irene',

    describe: function () {
        return 'Person named '+this.name;  // (1)
    },  // (2)
};

Enter fullscreen mode Exit fullscreen mode
  • Use this in methods to refer to the current object (also called the receiver of a method invocation).
  • in ECMAScript 5 allows a trailing comma (after the last property) in an object literal.
  • A trailing comma is useful, because it helps to rearrange properties without having to worry which property is last.

You may get the impression that objects are only maps from strings to values. But they are more than that: they are real general-purpose objects, we can use inheritance between them.
For example with the Prototype relationship between objects
The prototype relationship between two objects is about inheritance: every object can have another object as its prototype. Then the former object inherits all of its prototype’s properties.

But for now let's stay focus on the basics.

Create an object

In JavaScript object is a collection of properties where each property has a value associate with the key.
Use curly brackets {…}to create an object.

Pay attention to the following:

let empty = {};
Enter fullscreen mode Exit fullscreen mode

To create an object with properties, using the key : value pair.

let mobile = {
    name: 'apple',
    model: 's7',
    price: ' β€Žβ‚¬800'
};
Enter fullscreen mode Exit fullscreen mode

The mobile object has three properties name, model, and price with the corresponding values 'apple', 's7' and ' β€Žβ‚¬ 800'.

Accessing objects properties

There are two ways to access the property of an object, see the following: the dot notation and array-like notation.

The dot notation (.)

The following syntax shows how to use the dot notation to access a property of an object:

objectName.propertyName
Enter fullscreen mode Exit fullscreen mode

In order to access the name property of the mobile object, you use the following expression:

mobile.name
Enter fullscreen mode Exit fullscreen mode

The following snippet creates a mobile object and console name and model of mobile objects:

let mobile = {
    name: 'apple',
    model: 's7',
    price: 'β€Žβ‚¬800'
};

console.log(mobile.name);
console.log(mobile.model);
Enter fullscreen mode Exit fullscreen mode

Array-like notation ( [])

The following syntax shows how to access the value of an object’s property via the array-like notation:

objectName['propertyName'];
Enter fullscreen mode Exit fullscreen mode

for example:

let mobile = {
    name: 'apple',
    model: 's7',
    price: '€800'
};

console.log(mobile['name']);
console.log(mobile['price']);
Enter fullscreen mode Exit fullscreen mode

Suppose, you have property with contains spaces, you need to place it inside quotes.

Pay attention the following:

let homeAddress = {
   'house nom': 39,
    street: 'GΓΆtelstr.',
    state: 'Berlin',
    country: 'Germany'
};
Enter fullscreen mode Exit fullscreen mode

To access the 'house nom', you must use the array-like notation:

homeAddress['house nom'];
Enter fullscreen mode Exit fullscreen mode

If you use the dot notation, you will get an error:

homeAddress.'house nom';
Enter fullscreen mode Exit fullscreen mode

Reading from a property that does not exist will result in an undefined. For example:

console.log(homeAddress.district);

// Output: undefined
Enter fullscreen mode Exit fullscreen mode

Change the property’s value
To change the value of a property, you use the assignment operator. For example:

let mobile = {
    name: 'apple',
    model: 's7',
    price: '€800'
};

mobile.name = 'Motorola';

console.log(mobile);

//Output: {name: "Motorola", model: "s7", price: "€800"}
Enter fullscreen mode Exit fullscreen mode

Add a new property to an object

The following expression adds the weight property to the mobile object and assigns 150g to it:


let mobile = {
    name: 'apple',
    model: 's7',
    price: '€800'
};

mobile.name = 'Motorola';

mobile.weight= '150g';

console.log(mobile); 

// {name: "Motorola", model: "s7", price: "€800",
 weight: "150g"}
Enter fullscreen mode Exit fullscreen mode

Delete a property of an object

Using delete operator, To delete a property from an object:


delete objectName.propertyName;
Enter fullscreen mode Exit fullscreen mode

The following example removes the price property from the mobile object:

delete mobile.price;
Enter fullscreen mode Exit fullscreen mode

How to check if a property exists:

Using the in operator, You can check if a property exists in an object:


propertyName in objectName

Enter fullscreen mode Exit fullscreen mode

The following example creates a mobile object and uses the inoperator to check if the model and weight properties exist in the object.


let mobile = {
    name: 'apple',
    model: 's7',
    price: '€800'
};

console.log('model' in mobile);
console.log('weight' in mobile);

// Output:
true
false

Enter fullscreen mode Exit fullscreen mode

Iterate over properties of an object using for...in loop

πŸ›‘ To iterate over all properties of an object without knowing property names, you use the for...inloop, have a look at the following syntax:


for(let key in object) { 
    // ...
};
Enter fullscreen mode Exit fullscreen mode

The following shows, to creates abookobject and iterates over its properties using the for...in loop:

let book = {
    title: 'JavaScript',
    tags: ['es6', 'javascript', 'node.js'],
    price: '€35'
};

for (const key in book) {
    console.log(book[key]);
}
Enter fullscreen mode Exit fullscreen mode

Functions

The following syntax shows how to tag function to the book object:

let book = {
    title: 'JavaScript',
    price: '€35'
};

book.tag = function () {
   return ['es6', 'javascript', 'node.js']
}

console.log(book.tag());

//Output: ["es6", "javascript", "node.js"]
Enter fullscreen mode Exit fullscreen mode

In this example, a function expression is added to create the function and assigned it to the property tag of the book object.

Then, the function is called via the tag property as tag().
πŸ›‘When a function is a property of an object, it is called a method.

In ES6, you can even make it more concise:


let book = {
    title: 'JavaScript',
    price: '€35',
    tag() {
        return ['es6', 'javascript', 'node.js']
    }
};

console.log(book.tag());

Enter fullscreen mode Exit fullscreen mode

The this object properties

Suppose you have an array and you want to concatenate two objects properties inside the function, you can use this object properties.

πŸ›‘ Inside the method, the this value references the object that contains the method so you can access an object property using the dot notation:

this.propertyName
Enter fullscreen mode Exit fullscreen mode

The following example uses the this value in the getName() method:


let ps = {
    firstName: 'Irene',
    lastName: 'Smith',
    getName: function () {
        return this.firstName + ' ' + this.lastName;
    }
};

console.log(ps.getFullName());

//Output: Irene Smith

Enter fullscreen mode Exit fullscreen mode

RECAP

In this article, you have learned the following:

  • An objectis a collection of properties where each property has a value associate with thekey. An object property key is a string and value can be any valid value.
  • Use the dot notation( .) or array-like notation ([]) to access an object property.
  • The delete operator removes a property from an object.
  • The inoperator check if a property exists in an object.
  • The for...in iterates over properties of an object.
  • When functions are properties of an object, they are called methods.
  • Use the this inside the method to access the object’s properties.

I have written this article as a student's guide for my workshop aboutJavaScript Objects organised for DCI new students.

Happy coding!

Top comments (0)