Please enable JavaScript to use CodeHS

CodeHS Glossary


Constant JavaScript

A constant is a variable you define at the top of the program that doesn't change. The reason to define constants is to store named variables that have relevant values for the program. You define constants at the **top of the program** using `ALL_CAPS_WITH_UNDERSCORES`, unlike normal variables, which use [`lowerCamelCase`][1] One of the main reasons you use constants is to avoid using [magic numbers][2] in your code. ---------- **Examples:** 1: If part of your program is choosing a number, you should define constants to say the minimum and maximum values of the number like this: var MIN = 1; var MAX = 10; function start() { var n = readInt("Pick a number between " + MIN + " and " + MAX); } 2: If you're making a drawing, you'll want to use constants to define the size of certain objects like this: var SUN_RADIUS = 40; var GROUND_WIDTH = 400; var GROUND_HEIGHT = 100; ... 3: You can use constants to represent values you store as well, like in this program that moves a snake. Here, the constants of directions represent the direction the snake is moving in, so you know how much to move it. It also uses a constant called `SPEED` to determine what the speed the snake will move at. // constants for directions var EAST = 0; var NORTH = 1; var WEST = 2; var SOUTH = 3; // constant for speed var SPEED = 5; // global variables var direction; var snake; function moveSnake() { if (direction == EAST) { snake.move(SPEED, 0); } else if (direction == NORTH) { snake.move(0, -SPEED); } ... } Note how the global variables are in lower case even though they are global. The constants are the only ones that are in `ALL_CAPS` [1]: http://codehs.com/glossary/term/1 [2]: http://codehs.com/glossary/term/14