Geeks for Geeks says,
This article is a basic introduction to objects. I will not be going over objects in-depth, but I will be informing you of the parts I use most frequently to get you up and running quickly. For a more in-depth description of objects, I recommend MDN Working with Objects.
What is an Object?
MDN defines an object as:
“An object is a collection of properties, and a property is an association between a name (or key) and a value. A property’s value can be a function, in which case the property is known as a method.”
Let’s break this definition down.
"An object is a collection of properties", like:
In the example above, the object
footballPlayer has properties of name, position, jerseyNumber, and team. These properties are known as keys and the corresponding strings or numbers beside them are known as values. Together, each key and value make up a key-value pair.
The second part of the MDN object definition says
"A property's value can be a function, in which case the property is known as a method."
To simplify, this means a function inside an object is called a method. See the throw method/function in the example below:
Throw is a function that takes no parameters and console logs out the action of the player, which is “football was thrown [random integer under 61] yards”. Since this function is inside of an object, it is referred to as a method.
To call the throw method, you would type
What can you do with Objects?
Objects are great for data. With objects, you can mock a database for examples/prototyping, retrieve Web API data, or store/retrieve NoSQL Database data (MongoDB).
Don’t forget the obvious: You can use a programming paradigm called
Object Oriented Programming which uses objects.
Display data from Objects
One way is to call the object name and use dot notation:
Another way is to use bracket notation:
For iterating through objects with arrays:
You can assign values by using dot notation. You can overwrite a previous property’s value or create a new property and value.
You can also use