Lesson 4: Objects
In JavaScript, an object is a way to store multiple related pieces of data together. Instead of keeping separate variables for each value, we can group them into one object.
The snippet below shows code where we have related information spread across multiple variables. We don't want our code to look like this. It's cluttered, difficult to read, and that makes it easy to make mistakes. In fact, can you see the mistake in the code? Hint: it's highlighted, so hover over it for an explanation.
Compare the above code (which uses eight number and string variables) to this cleaner version that uses two objects.
Objects use key-value pairs, where each key (like eyeColor) is followed by a colon and its corresponding value. Properties inside an object are separated by commas.
You might be wondering how we can access those properties now that they are nested inside of the object. In JavaScript, we access object properties using dot notation. That just means you use dots to get inside of an object. For example, person2.name will access the value "Alex".
Write JavaScript code to create an object named settings that has two properties:
Make sure your object follows the correct syntax using {} and colons (:), and remember to separate properties with commas.
If you're having trouble with this exercise, here are some common mistakes and hints to help you out:
| Mistake | Hint |
|---|---|
| Using square brackets instead of curly braces | Objects must be created with { }, not [ ]. |
| Forgetting to use var when declaring the object | Always use var when declaring a variable for the first time. |
| Forgetting to use colons (:) between property names and values | Each property in an object must use a colon, not an equals sign. |
| Accidentally adding a comma after the last property | There should be no extra comma after the last property in an object. |