BETAThis is a new service – your feedback will help us to improve it.

Variables

So far, we've been making fairly simple programs that have only a single step.

If we wanted to make more capable programs, we'd struggle with what we've learned so far.

Declaring variables

Let's say we want to calculate a user's likely age based on the current year and a stored year of birth.

Although this would be possible with what we've learned so far, the resulting code would be very hard to read.

Javascript allows us to save data as variables to reuse later.

We can use the keyword const to start declaring (saving) variables.

const yearOfBirth = 1988
const thisYear = 2018

In the above example, we've saved two numbers as variables, calling them yearOfBirth and thisYear.

Variable names can't include any spaces, so we use a style called camel case to make them readable: the first word is all lowercase, and any other words start with an uppercase letter.

Using variables

const yearOfBirth = 1988
const thisYear = 2018

console.log(thisYear - yearOfBirth)

We've can now do a simple subtraction on those two variables to work out the user's likely age (30 in this case) and print it to the console.

We only use the const keyword when we initially create the variable. When we refer to it, we can just use its name.

Reassigning variables

These two variables are unlikely to need to change while the program is running, but there are plenty of situations where a variable might start out as one thing, but need to be turned into another.

If we know that we're going to have to reassign a variable later, we use the let keyword instead of const.

Everything else works the same way.

let currentYear = 2011

currentYear = new Date().getFullYear()

console.log(currentYear)

In this block of code, we declare a variable for the year, and temporarily set it to 2011. In the next line of code, we reassign the currentYear to whatever the actual year is.

We should see the current year (not 2011) printed to the console.

new Date().getFullYear() uses a built-in feature of Javascript to get the current year from your computer. Don't worry about how it is formatted for now.

In other peoples' code, you may see the keyword var used instead of const and let. This does the same thing, but is no longer the recommended way of declaring variables.

Lessons last updated 12th July 2019. You can improve this lesson on Github.
Part of Adding interactivity
  1. Introducing Javascript
  2. Your first Javascript program
  3. Variables
  4. Conditional logic
  5. Affecting the page
  6. Making a menu
  7. Responding to user actions
  8. Keep your Javascript accessible
  9. Get confident with Javascript
  10. Add interactivity to your prototypesP