Variables

Most useful programs need to track a value as it changes over the course of the program, undergoing different operations as called for by your program’s intended tasks.

The easiest way to go about that in your program is to assign a value to a symbolic container, called a variable — so called because the value in this container can vary over time as needed.

In some programming languages, you declare a variable (container) to hold a specific type of value, such as number or string. Static typing, otherwise known as type enforcement, is typically cited as a benefit for program correctness by preventing unintended value conversions.

Other languages emphasize types for values instead of variables. Weak typing, otherwise known as dynamic typing, allows a variable to hold any type of value at any time. It’s typically cited as a benefit for program flexibility by allowing a single variable to represent a value no matter what type form that value may take at any given moment in the program’s logic flow.

JavaScript uses the latter approach, dynamic typing, meaning variables can hold values of any type without any type enforcement.

As mentioned earlier, we declare a variable using the var statement — notice there’s no other type information in the declaration. Consider this simple program:

  1. var amount = 99.99;
  2. amount = amount * 2;
  3. console.log( amount ); // 199.98
  4. // convert `amount` to a string, and
  5. // add "$" on the beginning
  6. amount = "$" + String( amount );
  7. console.log( amount ); // "$199.98"

The amount variable starts out holding the number 99.99, and then holds the number result of amount * 2, which is 199.98.

The first console.log(..) command has to implicitly coerce that number value to a string to print it out.

Then the statement amount = "$" + String(amount) explicitly coerces the 199.98 value to a string and adds a "$" character to the beginning. At this point, amount now holds the string value "$199.98", so the second console.log(..) statement doesn’t need to do any coercion to print it out.

JavaScript developers will note the flexibility of using the amount variable for each of the 99.99, 199.98, and the "$199.98" values. Static-typing enthusiasts would prefer a separate variable like amountStr to hold the final "$199.98" representation of the value, because it’s a different type.

Either way, you’ll note that amount holds a running value that changes over the course of the program, illustrating the primary purpose of variables: managing program state.

In other words, state is tracking the changes to values as your program runs.

Another common usage of variables is for centralizing value setting. This is more typically called constants, when you declare a variable with a value and intend for that value to not change throughout the program.

You declare these constants, often at the top of a program, so that it’s convenient for you to have one place to go to alter a value if you need to. By convention, JavaScript variables as constants are usually capitalized, with underscores _ between multiple words.

Here’s a silly example:

  1. var TAX_RATE = 0.08; // 8% sales tax
  2. var amount = 99.99;
  3. amount = amount * 2;
  4. amount = amount + (amount * TAX_RATE);
  5. console.log( amount ); // 215.9784
  6. console.log( amount.toFixed( 2 ) ); // "215.98"

Note: Similar to how console.log(..) is a function log(..) accessed as an object property on the console value, toFixed(..) here is a function that can be accessed on number values. JavaScript numbers aren’t automatically formatted for dollars — the engine doesn’t know what your intent is and there’s no type for currency. toFixed(..) lets us specify how many decimal places we’d like the number rounded to, and it produces the string as necessary.

The TAX_RATE variable is only constant by convention — there’s nothing special in this program that prevents it from being changed. But if the city raises the sales tax rate to 9%, we can still easily update our program by setting the TAX_RATE assigned value to 0.09 in one place, instead of finding many occurrences of the value 0.08 strewn throughout the program and updating all of them.

The newest version of JavaScript at the time of this writing (commonly called “ES6”) includes a new way to declare constants, by using const instead of var:

  1. // as of ES6:
  2. const TAX_RATE = 0.08;
  3. var amount = 99.99;
  4. // ..

Constants are useful just like variables with unchanged values, except that constants also prevent accidentally changing value somewhere else after the initial setting. If you tried to assign any different value to TAX_RATE after that first declaration, your program would reject the change (and in strict mode, fail with an error — see “Strict Mode” in Chapter 2).

By the way, that kind of “protection” against mistakes is similar to the static-typing type enforcement, so you can see why static types in other languages can be attractive!

Note: For more information about how different values in variables can be used in your programs, see the Types & Grammar title of this series.