A variable declaration consists of the keyword let, followed by the name of the variable (you get to decide that one), like this:
Declaring and using variables
This simply tells the interpreter that a variable exists, with the name "age". It doesn't yet have a value, but after declaring it, you can assign a value to it, like this:
let age; age = 42;
Of course, if you already know what value the variable should hold, you can assign it at the same time as declaring it, like this:
let age = 42;
You can even declare multiple variables, with different values, in the same line - just separate with a comma:
let name = "John Doe", age = 42, mail = "firstname.lastname@example.org";
After declaring one or several variables, you can use them and change them however you want to. Here's an example:
let name = "John Doe", age = 42; document.write("My name is: " + name + " and today is my birthday"); age = age + 1; document.write("I am now " + age + " years old");
In this example, I declare two variables and then start using them. I simply output the name, but then I change the age and then output that as well. As you can see, it's pretty simple.
Naming a variable
As mentioned, you get to decide what your variable is called. There are a couple of rules though:
- The variable name may only contain letters, digits and/or two special characters: The $ (dollar sign) and the underscore (_)
- The variable name can't start with a digit
- You can't use any of the keywords/reserved words as they are, but they can be a part of the variable name. So for instance, "break" is a keyword, meaning your variable can't be called "break", but it CAN be called "lunchBreak"
let userMailAddress = "email@example.com"; let aLongVariableNameWithManyWords = 42;
Think of variables as nicely sorted storage boxes with labels on them: You can store any piece of information in a variable and name it accordingly, so that you can later access and/or modify the contents of the variable. Variables are such an important part of programming and you will see them being used in a lot of the examples through this tutorial, and even more so in the real world, when you start writing code for yourself.