What is a Variable?

A JavaScript program needs to use values, and that is where variables come into play. A program stores data in variables and assigns a name to refer to them in your program. In this section, we'll look at how to "declare", "initialize", and "update" variables in JavaScript.

After reading this section, consider these questions: 

  • How would programs be written without variables?
  • What is the difference between "declaring" and "initializing" a variable?

Constants in JavaScript

Many programming languages have the concept of a constant – a value that once declared can't be changed. There are many reasons why you'd want to do this, from security (if a third party script changed such values it could cause problems) to debugging and code comprehension (it is harder to accidentally change values that shouldn't be changed and mess things up).

In the early days of JavaScript, constants didn't exist. In modern JavaScript, we have the keyword const, which lets us store values that can never be changed:

const daysInWeek = 7;
const hoursInDay = 24;

const works in exactly the same way as let, except that you can't give a const a new value. In the following example, the second line would throw an error:

const daysInWeek = 7;
daysInWeek = 8;