4 Static Object Methods I Wish I Knew About Sooner
Tags: webdev, beginners, codenewbie, javascript
Published: 2020-07-24 20:13:12

When it comes to writing code in JavaScript, objects are a massively important and useful part of the language. If you haven't learned about objects yet that's okay! You can think of an object as a way for us to create a collection of key-value pairs. For example, I have a first and last name, and a city I live in. These would be the keys of key-value pairs. The values would be the pieces of  information with first name being Sandrico, last name being Provo, and city being Halifax. Here is what that would look like inside an object.

``` javascript
let myInfo = {
  firstName: "Sandrico",
  lastName: "Provo",
  city: "Halifax"
}
```

Objects have sooooo many use cases in JavaScript, and the example above is just one scenario where you might use them. Another cool thing about objects is that whenever we make one it has a collection of methods attached to it called static methods. What are static methods you might ask 😃? Well, Static methods are pre-defined methods we have access to on every object. There is a master object class that every object inherits these methods from, somewhat like a blueprint. Another metaphor would be a car. Every car you buy these days has certain base features like a seat belt and steering wheel, and static methods are the same idea! When I started learning about objects I didn't learn about static methods until later. The static methods we are about to go through would have helped me a ton if I knew about them sooner, but now I hope they save you some time when coding 😄.

### TLDR
|Name|Description|
|:-----|:-----|
|JavaScript Object|A JS class that lets us define an object data type. It lets us create a collection of key-value pairs.|
|Object Static Methods|Methods that are pre-defined and called on the object class.|
|Object Instance Methods|Methods that are pre-defined and called on a single object instance.|
|Object.keys()|Returns an array of the objects keys.|
|Object.assign()|Copies a source objects properties to a target object.|
|Object.entries()|Returns an array of all the objects key-value pairs.|
|Object.fromEntries()|The opposite of .entries(), this turns a key-value pair list into an object.|
|Object.prototype.hasOwnProperties()|Returns true or false based on whether the object has the given key.|

# The Static Methods
Let's set up an example for us to work with.

```javascript
let countryCanada = {
	countryName: "Canada",
	capital: "Ottawa",
	region: "North America",
	population: 37590000,
	neighbour: "United States"
}
```

## Object.keys()
Sometimes when you're working with an object you might want to list all of its keys. Object.keys() is the method that lets us do this! When you use Object.keys() you get back an array that contains all of that objects' keys. Fun fact: the array that you get back should be in the same order as the object that the keys are in. Here's what this would look like in code.

```javascript
let propertiesArray = Object.keys(countryCanada);
// Output: ['countryName', 'capital', 'region', 'population', 'neighbour']
```

## Object.assign()
Sometimes you might want to make a copy of an object and its key-value pairs. Object.assign() lets us do this by copying key-value pairs from a source object to a target object. The target object can be empty or an object with its own properties already. If the target object has its own properties, you do need to be careful because if the source and target have a matching property the sources value will overwrite the targets value. Another tip is that you can also have multiple sources! Let's check out an example.

```javascript
// Make a copy using Object.assign()
let copiedCountry = Object.assign({}, countryCanada);
console.log(copiedCountry);
// Output: copiedCountry { countryName: "Canada", capital: "Ottawa", region: "North America", population: 37,590,000, neighbour: "United States" }
```

## Object.entries()
This static method allows you to convert your objects into arrays. If we did this with our example object, here is what the output would look like.

```javascript
let convertedCountryArray = Object.entries(countryCanada);
// Output: [["countryName", "Canada"], ["capital", "Ottawa"], ["region", "North America"], ["population", 37590000], ["neighbour", "United States"]]
```

As you can see, the output array is a 2D array (an array with arrays nested inside of it). One benefit of working with this object as an array is that you could use the vast array (🙊😅) of array methods to manipulate it. Now, you've converted this object into an array, but what if you want to convert it back into an object? Well, there is a method for that as well!

## Object.fromEntries()
You can think of this method as doing the reverse of Object.entries(). It takes an array and converts it into an object. If we used this on our counvertedCountryArray from our Object.entries() example, we would be back to our original object like so.  

```javascript
let reconvertedCountryArray = Object.fromEntries(convertedCountryArray);
console.log(reconvertedCountryArray);

// Output: countryCanada = { countryName: "Canada", capital: "Ottawa", region: "North America", population: 37590000, neighbour: "United States" }
```

An example of what this could allow us to do is manipulate this object using array methods. Let say we want a new object that only has the capital city in it. In combination with Object.entries(), we could use this method to achieve this. Here is an example of what I mean.

```javascript
let manipulatedObject = Object.fromEntries(
  Object.entries(countryCanada).filter(([key, value]) => { 
    if (value === "Ottawa") return [key, value];
  }
));
// Output: { capital: "Ottawa" }
```

## Bonus: Object.prototype.hasOwnProperty() Instance Method
Here are a two terms that'll help explain our bonus example.

|Name|Description|
|:-----|:-----|
|Prototype|The prototype is what JS objects use to inherit methods/functions and other features from one another.|
|Instance Method|Instance methods are methods built onto objects that run on the particular instance of an object instead of the object class.|

Object.prototype.hasOwnProperty() is a useful method because it allows us to check whether or not the object we are working with has a particular property in it. An important fact to remember is that this method checks if the object owns the property we're looking for as *oppose to inheriting it*. Here is an example. 

```javascript
let isPropertyOwned = countryCanada.hasOwnProperty("capital");
console.log(isPropertyOwned);
// Output: true
```

Like many things in coding there are multiple ways you could do a check like this, but it's nice to have a built-in function to help you out 👍🏾. 

# Well That Was Fun 😄
There we are. We've looked at Object.keys(), .assign(), .entries(), .fromEntries() and .hasOwnProperty().  These methods could have saved me time when I was starting out, so hopefully they help you save some time in your journey. 

Happy Learning 😄👋🏾!