Coding with Objects
Booleans and Objects
Objects are not stored by their properties or by value, but by
Storing something by reference means that it is stored based on its location
in memory. This can lead to some confusion when comparing objects.
Let’s see how this affects our zoo software! Surely, the zoo has more than one tortoise. The second tortoise is named Patricia!
Because Pete and Patricia are members of the same species, are the same age, and have the same diet, you might notice that many of their properties are equal, but some are not. Pete weighs more than Patricia and of course, they have different names!
For this example, we will only keep the
The objects contain properties that have the same keys and equal values.
However, the output is
tortoiseTwo have the same keys and values,
they are stored in separate locations in memory. This means that even though
you can compare the properties in different objects for equality, you cannot
compare the objects themselves for equality.
Iterating Through Objects
We can iterate through all of the values in an object, much like we would do
with an array. We will use a for loop to do that, but with a slightly
for...in loops are specifically designed to loop
through the properties of an object. Each iteration of the loop accesses a key
in the object. The loop stops once it has accessed every property.
species, Reticulated Giraffe name, Cynthia weight, 1500 age, 15 diet, leaves
In this example,
item is a variable that holds the string for each key. It is updated with each iteration of the loop.
for..in loop, we can only use bracket syntax to access the property values.
chapter-examples directory in the
ForInLoop.js, write a
for..in loop to print to the console the values in the
Objects and Functions
Programmers can pass an object as the input to a function, or use an object as the return value of the function. Any change to the object within the function will change the object itself.
On line 16, when the
birthday function is called,
giraffe is passed in as an argument and returned. After the function call,
giraffe.age increases by 1.
Check Your Understanding
What type of loop is designed for iterating through the properties in an object?
Given the following object definitions, which statement returns
tortoiseOne == tortoiseTwo
tortoiseOne === tortoiseTwo
tortoiseOne.age === tortoiseTwo.age