Learning JavaScript | Objects
Objects in JavaScript hold a collection of properties tied together by key values, making each item in an object a key pair value. The key is the “identifier”, and the contents are the “property” value. Objects can hold primitive variables, functions, or other objects as valid properties.
Instantiating an Object
We can create an instance of an object type using the predefined Object class that comes with JavaScript
const car = new Object() // using the 'new' keywordWhen using the new keyword we can still attach properties to the object like so:
const car = new Object();
car.carName = "fun car";
// Anonymous function
car.someMethod = function () {
return "Hello World";
};
// Named Function
car.someOtherMethod = function someOtherMethod() {
return "Hello Earth";
};
console.log(car);
// Prints the object below
// {
// carName: 'fun car',
// someMethod: [Function (anonymous)],
// someOtherMethod: [Function: someOtherMethod]
// }Or we can use the JSON syntax with Curly braces.
const car = {...} // using {} curly bracketsWe can initialize the same object by using curly brackets like so:
const car = {
carName: "fun car",
someMethod: function () {
return "Hello World";
},
someOtherMethod: function () {
return "Hello Earth";
},
};
console.log(car);
// Prints the object below
// {
// carName: 'fun car',
// someMethod: [Function: someMethod],
// someOtherMethod: [Function: someOtherMethod]
// }Objects provide us a way to map items to a key in a list of values. For example, a car could have the keys: color, make, model, year, and each key would have some value, like: red, Honda, Civic, 2012. As in object we can write this as so:
const car = {
color: "red",
make: "Honda",
model: "Civic",
year: 2012,
};Once we define an object we can reference the items inside the object
const car = {
color: "red",
make: "Honda",
model: "Civic",
};
console.log(car.color); // Returns "red"
console.log(car["model"]); // Returns "Civic"JavaScript Object Notation(JSON)
Quick call out here before we continue. You may be familiar with JSON, if so, this is exactly what JavaScript objects use to describe objects. If you aren't familiar though, lets go through some usage examples and syntax
JSON is mostly used as a config file, or a response / request from or to an API. A configuration file we often see when working on a Node.js project is the package.json file.
Running npm init -y will generate the below configuration file, written in JSON, you can see its very similar to what we just talked about with JavaScript Objects.
{
"name": "test-sheet",
"version": "1.0.0",
"description": "",
"main": "test.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {}
}All valid JSON must be wrapped in square brackets([]), or curly brackets({}). In this case since we are assigning a key and a value(1:1), we use curly braces, if we were to represent a list of values assigned to a single key(1:many) then we would use square brackets
Get Harold’s stories in your inbox
Join Medium for free to get updates from this writer.
Here is an example where we use square brackets, in this example we have a list of ID cards. The ID cards are made up of objects with key pair values which makes essentially an array of objects, or list of values
[
{
"id": 1,
"name": "Card 1",
"description": "Card 1 description",
"list_id": 1
},
{
"id": 2,
"name": "Card 2",
"description": "Card 2 description",
"list_id": 2
}
]I wanted to make this quick call out since often time I see a lot of confusion between JSON and JavaScript objects, but actually they are represented in the same way
Working with Objects
A couple of common uses for Objects are:
- When declaring objects through a class
- When sending the body of an HTTPS request
- when receiving an HTTPS payload
Lets go through getting an HTTPS request from the PokéAPI, the PokéAPI has a collection of just about all Pokémon, and Pokémon items from many of the games.
// send out the request
const res = await fetch("https://pokeapi.co/api/v2/pokemon?limit=10");
// log the request as a JSON object
const json = await res.json();
// the JSON response
// {
// count: 1281,
// next: 'https://pokeapi.co/api/v2/pokemon?offset=10&limit=10',
// previous: null,
// results: [
// { name: 'bulbasaur', url: 'https://pokeapi.co/api/v2/pokemon/1/' },
// { name: 'ivysaur', url: 'https://pokeapi.co/api/v2/pokemon/2/' },
// { name: 'venusaur', url: 'https://pokeapi.co/api/v2/pokemon/3/' },
// { name: 'charmander', url: 'https://pokeapi.co/api/v2/pokemon/4/' },
// { name: 'charmeleon', url: 'https://pokeapi.co/api/v2/pokemon/5/' },
// { name: 'charizard', url: 'https://pokeapi.co/api/v2/pokemon/6/' },
// { name: 'squirtle', url: 'https://pokeapi.co/api/v2/pokemon/7/' },
// { name: 'wartortle', url: 'https://pokeapi.co/api/v2/pokemon/8/' },
// { name: 'blastoise', url: 'https://pokeapi.co/api/v2/pokemon/9/' },
// { name: 'caterpie', url: 'https://pokeapi.co/api/v2/pokemon/10/' }
// ]
// }If we break it down the response is just an object and like any object we can access the values using dot notation
console.log(json.count); // returns 1281
console.log(json.results); // returns [
// { name: 'bulbasaur', url: 'https://pokeapi.co/api/v2/pokemon/1/' },
// { name: 'ivysaur', url: 'https://pokeapi.co/api/v2/pokemon/2/' },
// { name: 'venusaur', url: 'https://pokeapi.co/api/v2/pokemon/3/' },
// { name: 'charmander', url: 'https://pokeapi.co/api/v2/pokemon/4/' },
// { name: 'charmeleon', url: 'https://pokeapi.co/api/v2/pokemon/5/' },
// { name: 'charizard', url: 'https://pokeapi.co/api/v2/pokemon/6/' },
// { name: 'squirtle', url: 'https://pokeapi.co/api/v2/pokemon/7/' },
// { name: 'wartortle', url: 'https://pokeapi.co/api/v2/pokemon/8/' },
// { name: 'blastoise', url: 'https://pokeapi.co/api/v2/pokemon/9/' },
// { name: 'caterpie', url: 'https://pokeapi.co/api/v2/pokemon/10/' }
// ]Object Destructuring
Now, another cool thing we can do with objects is destructure them, and pull out the values we need without the dot notation. This is a very useful way of keeping your code clean, and only using what you need from a response. In this case lets destructure the results array from our PokéAPI call
// send out the request
const res = await fetch("https://pokeapi.co/api/v2/pokemon?limit=10");
// log the request as a JSON object
const { results } = await res.json();The const { results } syntax is where we destructure the whole object into only returning the results array that we are looking for. Then we can use results just like any other variable.
Closing thoughts
Objects represent some thing with key pair values, it could be a car, cat, pokemon, or anything else, and we can use them to make HTTPS request, receive HTTPS responses, and as part of OOP through classes.





