Don't Use Two If One Will Do

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.

Example

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".

Your Task

Write JavaScript code to create an object named settings that has two properties:

  • delay: A number representing the delay time in milliseconds. The ball will wait this many milliseconds before switching to a new color.
  • colors: An array containing at least three different colors of your choice.

Make sure your object follows the correct syntax using {} and colons (:), and remember to separate properties with commas.

Hints

If you're having trouble with this exercise, here are some common mistakes and hints to help you out:

MistakeHint
Using square brackets instead of curly bracesObjects must be created with { }, not [ ].
Forgetting to use var when declaring the objectAlways use var when declaring a variable for the first time.
Forgetting to use colons (:) between property names and valuesEach property in an object must use a colon, not an equals sign.
Accidentally adding a comma after the last propertyThere should be no extra comma after the last property in an object.