Constants

advertisement
Constants
Corresponding Material
Basic JavaScript, Lesson 4
Discussion
Variables get their name from the fact that they vary, or change.
A constant, however, does not change its value. It’s constant!
What constants do you use everyday?
How and why to use a constant
Constants are helpful in many programming situations. We can
create a constant by declaring or initializing it before the start
function. Constants also are named in all capital letters. Using
constants makes our code more readable than writing raw
numbers.
For example, if we have a program to calculate the number of
minutes in a given number of hours, we could create a constant
like MINS_IN_HOUR that holds the number 60. There will also be
60 minutes in an hours, so this is a good place for a constant.
Class Exercise
The program below computes how much money the user has in
quarters. Fill in the blanks to create and use a constant in the
program:
// Create a constant for the value of a quarter
var __________________ = _____;
// Calculate the value in cents of a number of quarters
function start(){
var __________________ = readInt("How many? ");
var total = __________________ * __________________;
println("Total value in cents: " + total);
}
Download