Objects
The other category of data we can store in variables are objects.
Objects
A web application usually deals with more complex data than the primitive data value types provide. JavaScript allows you to build more complex objects out of the primitive data types. An object is just a collection of property-value pairs to describe the data unique to the object.
For example, an object to represent a user would likely have properties such as the first and last name, the user name, and the email address, among others.
The object can be as complex as you need it to be. For example, the user object above could contain an embedded object representing the address, rather than just a string.
Dot Notation for Accessing Properties
Default way for accessing properties.
Shopping Cart Example
We're all familiar with online shopping and the concept of a shopping cart. The user selects items they intend to buy and those items are stored in what is called a "cart". When you are ready to check-out, you get a view of everything in your cart, and the total that it will cost. We're going to work through how to represent that data.
Each item that can be purchased has multiple pieces of data that need to be stored together. So we create an object that aggregates that data together in one data structure.
A data structure is a collection of data values, the relationships among them, and the functions or operations that can be applied to the data. - Wikipedia
Above, we've created the object directly in our JavaScript code. For data such as this, it would be more likely that the data about the products would be initially defined and stored in a database and the JavaScript code would call a function that would request the data from the web API.
Here's a real-world example of the NY Times website calling the webAPI for its site to retrieve all of the top stories in the arts section.
So, typically you would receive an array of items.
Now, let's implement our shopping cart.
An object can have properties whose value is a function. A function is a special kind of object.
Just like you can access a property within an object, you can do the same to execute a function within an object.
Last updated
Was this helpful?