JavaScript Objects 🤔 💻
Published: 2020-07-29 09:40:07


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. 
<b> There are three kinds of properties:</b>

- <b>Properties (or named data properties)</b>
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.
- <b>Accessors (Getters/Setters) </b>(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.
- <b>Internal properties</b>
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:
```javascript
let irene = {
    name: 'Irene',

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

```
- 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.

<b> Create an object</b>

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

Pay attention to the following:

```javascripts
let empty = {};
```
To create an object with properties, using the key : value pair.

```javascript
let mobile = {
    name: 'apple',
    model: 's7',
    price: ' ‎€800'
};
```
The mobile object has three properties name, model, and price with the corresponding values 'apple', 's7'   and ' ‎€ 800'.

<b>Accessing objects properties</b>

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

<b>The dot `notation (.) `</b>

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

```javascript
objectName.propertyName
```
In order to access the name property of the mobile object, you use the following expression:

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

```js
let mobile = {
    name: 'apple',
    model: 's7',
    price: '‎€800'
};
 
console.log(mobile.name);
console.log(mobile.model);
```
<b>Array-like notation ( []) </b>

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

```js
objectName['propertyName'];
```
for example:
```js
let mobile = {
    name: 'apple',
    model: 's7',
    price: '€800'
};
 
console.log(mobile['name']);
console.log(mobile['price']);
```
Suppose, you have property with contains spaces, you need to place it inside quotes.

Pay attention the following:

```js
let homeAddress = {
   'house nom': 39,
    street: 'Götelstr.',
    state: 'Berlin',
    country: 'Germany'
};
```
To access the 'house nom', you must use the <b> array-like notation</b>:

```js
homeAddress['house nom'];
```
If you use the dot notation, you will get an error:

```js
homeAddress.'house nom';
```
Reading from a property that does not exist will result in an undefined. For example:

```js
console.log(homeAddress.district);

// Output: undefined
```
<b>Change the property’s value </b>
To change the value of a property, you use the assignment operator. For example:

```js
let mobile = {
    name: 'apple',
    model: 's7',
    price: '€800'
};
 
mobile.name = 'Motorola';
 
console.log(mobile);

//Output: {name: "Motorola", model: "s7", price: "€800"}
```
<b>Add a new property to an object </b>

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

```javascript

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"}
```

<b> Delete a property of an object</b>

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

```javascript

delete objectName.propertyName;
```

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

```javascript
delete mobile.price;
```
<b> How to check if a property exists:</b>

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

```javascript

propertyName in objectName

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

```javascript

let mobile = {
    name: 'apple',
    model: 's7',
    price: '€800'
};
 
console.log('model' in mobile);
console.log('weight' in mobile);

// Output:
true
false

```
<b> Iterate over properties of an object using `for...in` loop</b>

🛑 To `iterate` over all properties of an object without knowing property names, you use the `for...in `loop, have a look at the following syntax:

```javascript

for(let key in object) { 
    // ...
};
```
The following shows, to creates a` book `object and iterates over its properties using the `for...in` loop:

```javascript
let book = {
    title: 'JavaScript',
    tags: ['es6', 'javascript', 'node.js'],
    price: '€35'
};
 
for (const key in book) {
    console.log(book[key]);
}
```
<b>Functions</b>

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

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

//Output: ["es6", "javascript", "node.js"]
```
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()`. 
 🛑<b>When a function is a property of an object, it is called a method.</b>

In ES6, you can even make it more concise:
```javascript

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

```
<b>The `this ` object properties </b>

Suppose you have an <b>array </b> 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:

```javascript
this.propertyName
```
The following example uses the this value in the getName() method:

```javascript

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

//Output: Irene Smith

```
<b> RECAP </b>

In this article, you have learned the following:

- An `object `is a collection of properties where each property has a value associate with the` key`. An object property key is a string and value can be <b>any valid value.</b>
- Use the dot notation` ( .)` or array-like notation ` ([])` to access an object property.
- The delete operator removes a property from an object.
- The `in `operator 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](https://digitalcareerinstitute.org/courses) new students.
<!--![Alt text of image](put-link-to-image-here)-->
Happy coding!

<img src="https://media.giphy.com/media/13HgwGsXF0aiGY/giphy.gif" alt="" loading="lazy">