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 ofconst
andlet
. This does the same thing, but is no longer the recommended way of declaring variables.
Part of Adding interactivity
- Introducing Javascript
- Your first Javascript program
- Variables
- Conditional logic
- Affecting the page
- Making a menu
- Responding to user actions
- Keep your Javascript accessible
- Get confident with Javascript
- Add interactivity to your prototypesP