Sample Video Frame

Created by Zed A. Shaw Updated 2024-02-17 04:54:36

06: Variables

In programming there's a concept of a "magic number". This is a number that's some constant or setting which is simply sitting there in the code with no explanation as to what it is, or why it is that number. Programmers over the years have learned to hate magic numbers for three reasons:

  1. Magic numbers don't explain what they are or why the exist. You just see 0xDEADCAFE and think, "What? Why did someone use this number here."
  2. Magic numbers are difficult to update and fix later. Imagine you now have to be 100% positive you've replaced all 0xDEADCAFE numbers with 0x5637CC. Now you have to search and replace all over, but what if 0xDEADCAFE is used for more than one thing? Now you can't just replace them, you have to check each one.
  3. Magic numbers simply don't scale as the code and team of people grows. Cognitively it's difficult to keep all of the magic numbers in one person's head, let alone correctly share this information with others reliably. As the quantity of magic numbers increases, your ability to remember each one diminishes.

The solution programmers have for magic numbers is to simply give them name like this:

image_tag = 0xDEADCAFE

Now, anywhere they write the word image_tag the compiler (computer) will replace it with 0xDEADCAFE. Suddenly we've solved several problems:

  1. If I need to update the image tag, I go to this variable and change only one thing.
  2. If another part of the system uses 0xDEADCAFE for another purpose, my changes to image_tag won't change their code.
  3. I don't have to remember what 0xDEADCAFE is used for since now image_tag is a name describing what it is.

In CSS we now have this same ability, but why do I say "now we have this ability"?

Previous Lesson Next Lesson

Register for Learn JavaScript the Hard Way

Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.