Sunday, January 4, 2009

Constants: Beyond Stubborn

Think back to 8th or 9th grade Algebra I, and you'll remember that in addition to "variables" there are "constants." The constants always bored me, they made it impossible to be creative in math class. But in programming (and heck, in normal math too) they're important. Some things don't change, and it's easier to set a constant and reuse it over and over again.

If you ever want to change the value of that constant, you can do it in one place, instead of all throughout your code. The textbook example, which seems like a good one to use and remember, is a constant tax rate in the equation of figuring out how much tax is owed on a purchase. The tax rate doesn't change, so it's a constant, not a variable.

Constant's JavaScript keyword is longer than the one for variable (var)...

const: the JS keyword for constant

const CONSTANTNAME = CONSTANTVALUE;
Formatting Note:
Constants are written in ALL CAPS and Variables are written in MixedCase.
If your constant changes at some point down the road, you can always go back and change it in your script. It just can't change while the script is running.

***like variables, constants can be named just about anything, but their name must start with a letter, $, or _

No comments:

Post a Comment