Mastering objects in Javascript
Tags: javascript, typescript, node
Published: 2023-06-29 08:27:19

The object data structure is used to express real-life objects, just like a car is an object with a wheel property, a color property, a brand property, and so on thus a car in Javascript can be an object with these properties.

Objects are not unique to Javascript and work just like objects in other programming languages. 


In today's post we are going to explore objects in Javascript, we will take a look at the following, starting with;

- What objects are.
- How to access object properties.
- Using functions as object values.
- Deleting Object properties.
- Four different ways to create Objects in Javascript

## What are objects

An object is a data structure that stores a collection of comma-separated key:value pairs. A key:value pair is collectively known as property. An object is expected to have at least one property for it to be considered a valid object.

To create a simple object in Javascript you can use the object literal expression. The object literal expression refers to a comma-separated key:value pairs enclosed within paired curly brackets. let's see an example.

```javascript
const obj = {
  name: 'Sam',
  age: 30,
  employed: false
};

console.log(obj);
// {name: 'Sam', age: 30, employed: false};
```
We create an object using the object literal expression by creating a variable named `obj`. The first property on this object is a name property which has a value of `Sam`, the second property is an `age` property which has a value of `30`. The last property is an `employed` property which has a value of `false`.

Let's log out this variable to the console to see what it looks like.

The object created above is an example of a Javascript object, this is also what is known as an object literal. The object has three properties. Each has the appropriate value for that key, from this example, it can be observed that the value for a key on a Javascript object can be any of the primitive data types supported by Javascript.

Now we have seen what objects are in Javascript, let's see how we can access object properties.

### How to access object properties

```javascript
const name = obj.name
console.log(name)
// Sam
const age = obj['age'];
console.log(age);
// 30
```

There are two ways for accessing the properties declared on an object. 

- Dot notation
- Square bracket Notation

In the example above we use the dot notation to access the name property declared on the object, then we store it inside a variable called `name`.  We log out this variable to the console and we see that is value `Sam`.

To use the square brackets notation you put an opening and a closing square bracket right after you the object then, inside paired single or double quotes you enter the key for the property you want to access,  in this instance, we are concerned with the `age` property. We store it inside a variable called age and log it out to the console and its value is `30`.

### Using functions as object property values

We can use functions for the value of a key on an object and let's look at an example of that;

```javascript
function sayHello() {
  console.log('Hello')
}

obj['greeting'] = sayHello;
obj.sayHello = sayHello;
```

We create a function called `sayHello` and this function just logs out the word `Hello` to the console. To store this function in an object we would set it to be the value of a key.

To add this function to the object we created earlier, we can use the square bracket notation to achieve this.

We want the object to have a `greeting` property and we assign it the `sayHello` function we created earlier.

We can also use the dot notation to do this and we assign a `sayHello` property a value which is the `sayHello` function.

```javascript
obj.greeting()
// hello
```

We can also use the square bracket notation if that's what we are more comfortable with.

### Deleting Object properties.

To delete an object property you can use the `delete` keyword together with the name of the property you want to delete. Say we wanted to delete the sayHello property we declared on the object.

```javascript
delete obj.sayHello;

console.log(obj)
// {name: "Sam", age: 30, isEmployed: false, greeting: f}
```

First comes the delete Keyword then the object and we use the dot notation to get access to the `sayHello` property, then we log out the obj to the console. And from the object we get we see that it doesn't contain that `sayHello` method anymore, only a greeting method. And properties whose values are functions are called methods.

## Creating objects in Javascript

### Using Object Assign

Object.assgin is used to clone an object, this method accepts two parameters. 

This method accepts two arguments(target, source), The first is the target object we are trying to create, and the second is the source object whose properties we want to clone.

```javascript
const sayHello = (name) => (`Hello ${name}`);
const Person = Object.assign({ 
	name: "sam",
	age: 25
},
{
	sayHello,
	title: "Mr"
})
console.log(Person);
// {name: "sam", age: 25  sayHello: f, title: "Mr"}
```
We clone an object with a title property and sayHello method (source) to an object with a name and age property (target).

### Using Object.create

Object.create is similar to the method we just discussed. However, it creates a new object, not a clone.

It only accepts one argument, an object that will serve as the prototype of the object we are creating.

```javascript
const sayHello: (name) => (`Hello ${name}`);
const Person = Object.create({
	sayHello,
	title: 'Mr',
});
Person.name = "Sam";
Person.name = 25
console.log(Person);
// { name: "sam", age: 25 }
```
The object created has a name property and an age property.

Using `Object.getPrototypeOf(Person)` will give an object with a title property and sayHello method. I particularly like using this approach.

```javascript
console.log(
 Object.getPrototypeOf(Person)
);
// {sayHello: f, title: "Mr"}
```

### new Object

You can use the built-in Object constructor to create an Object, the Object constructor function accepts an optional parameter.
An object whose property we want to copy onto the new Object. Using dot notation wouldn't be too intuitive. 

```javascript
Let Person = new Object({
	name: "sam",
	age: 25
})
console.log(Person);
// { name: "sam", age: 25 }
```
The object created has a name property and an age property.
Likewise, Object.getPrototypeOf(Person) will return an empty object.

### Object Literal
The simplest approach is to use an object literal expression to create an object.
An Object literal is just a collection of comma-separated keys:value pair.
example;

```javascript
const Person = { name: "sam", age: 30 }
```
You can wrap it in a function to make it reusable or have dynamic values, `Object.getPrototypeOf(Person)` will also return an empty object.

```javascript
const MakePerson = (name, age) => {
	return ({
		name,
		age
	})
}
const Person = MakePerson("sam", 25)
console.log(Person);
// { name: "sam", age: 25 }
```
Calling `Object.getPrototypeOf(Person)` will return an empty object because this method does not attach a prototype to the object.

That's it for this one guys. If you found this useful please leave your comments down below I will see you in the next one.