So, let's now see the Objects basics. 😎
We can fill an object with unordered data, called properties. A property is a key: value pair, where a key is a string (also property name), and value can be of any data type. A key is similar to a variable name that points to a location in memory that holds a value. The value can be any data type (including functions or other objects).
Accessing the Properties
There are two ways to access the object properties: Dot notation and Bracket Notation.
With the dot notation, we write the object’s name, the dot operator and then the property name:
With the bracket notation, we pass in the property name (key) as a string:
Assign to a property
Objects are mutable, which means that we can update them. We can use dot or bracket notation to select the property and with the help of the assignment operator, we can add new key-value pairs (if there was no property with that name) or change an existing property (if the property already exists). We can also delete a property from the object with the delete operator.
Methods as Properties
We can also include methods in our object literals; With the ES6 syntax we can include them in the object as:
*Pass by what? *
In JS when a function is called, it directly passing the value of the variable as the argument. Changing the variable inside the function doesn’t affect the variable passed. However, objects are passed by reference. When we pass a variable assigned to an object into a function, this is interpreted as pointing to the space in memory holding that object. As a result, functions can change this object permanently.
Iterating through Objects
Write 100% better code with 250k+ posts
Level up every day