You are familiar with the data types of strings and numbers. These data types are considered primitive since they only store one value at a time. This can be inconvenient when you need to work with sets of related information. Objects are used to work more efficiently with collections of values. This topic will explore what objects are and how they function.
Definition of object
An object is a non-primitive data type representing an unordered property collection. A property is a part of the object that imitates a variable. It consists of a key and a value separated by a colon. The key can only be a string or a Symbol (data type, which we will get acquainted with later), but the value may be of any data type. You can create empty objects without a single property:
let book = {};There is an alternative way to create an empty object, but it is rarely used in practice:
let book = new Object();You can check that both of these methods create an object using the typeof operator that you already know.
let book1 = {};
let book2 = new Object();
console.log(typeof book1); // object
console.log(typeof book2); // objectIf you want to create an object with several properties, all but the last must be followed by a comma. To understand the syntax better, take a look at the following example:
let country = {
name: "Netherlands",
population: 17.18
};As in many cases in JavaScript, object creation often starts with defining and initializing a variable. In the example above, we've assigned the object the name country. Then, two properties were specified in curly braces: the key name with the value Netherlands, and the population key with 17.18. As you can see, objects are handy for grouping data.
The syntax with curly braces used to create objects has its name: literal notation. It's not the only way to do it, but it's probably the most common.
Properties
Objects are one of the pillars of the JavaScript language, so it's important to know how to work with their properties.
There is an opportunity to refer to the properties. We use a record with the object name and a dot to access the properties. Let's use the previous code sample and try to access the
nameproperty:
console.log(country.name); // NetherlandsProperties can also be added using the dot symbol and the
=assignment symbol. Let's add to our object property with the keycapitaland theAmsterdamvalue :
country.capital = "Amsterdam";To delete a property, we can use the
deleteoperator and a dot. This is how removing thepopulationproperty for the object namedcountrywill look like this:
delete country.population;Read more on this topic in String Along with JavaScript Strings on Hyperskill Blog.
Conclusion
Working with grouped data is one of the most common tasks in programming. You now have an essential tool that will help you with that: objects and their properties. Way to go!