JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops The Refactor Challenge, Part 2

sebbe12
sebbe12
4,015 Points

Why is var red red

red is the variable name we give the variable and therefore means nothing? How can var red; be red when it's just a name.

2 Answers

Cody Selman
Cody Selman
7,642 Points

I believe you may be referring to the behavior in which a color-picker appears when you hover over the "red" variable's name. You may be misunderstanding some things that are happening here, so I'll do my best to clarify.

There are various ways to declare a color in HMTL. See this MDN documentation. The red variable is generating a random number between 0 and 256 to determine how much red will go into a random color using a notation as indicated in this example: "rgb(149, 235, 94)". The first number "149" is a random number specifying how much red to use in this rgb color value. The "235" is how much green, and the "94" is how much blue." The end result is a lighter green.

The reason the red color swatch appears when you hover your mouse over the variable name "red" is likely a feature of TreeHouse's code editor. It is a common feature for code editors to display the color or a color picker when hovering over a color name, rgb color-value, hex code for a color, etc. Despite the fact that a red color swatch appears when you hover your mouse over the variable name "red", the value that is actually stored in that variable is a random number between 0 and 256 and is not a color in its own right.

Steven Parker
Steven Parker
174,163 Points

You are correct that "red" is just the name of the variable. The program would work just the same if you changed the name to "yo" or "buzz". But it was chosen because it is used to build a color, and it represents the amount of red that will be mixed into the final color. Giving variables names that relate to what they are used for is helpful to anyone reading and trying to understand the code.

Later in the same video, all three of the variables with color names are replaced using a function that builds the color using random values.