Variables are containers for storing data values. Variables have to have a name and have to follow specific rules.
let myVariable. It is allowed to create variables without a value because we might not have the value yet, but we are going to get it later in the code.
If you create a variable like above, it has no value assigned. The assignment of a value to a variable is done by using
= symbol that is followed by the value we want to store in the variable.
let myVariable = 1;
The last thing we can provide is
; is an optional symbol, you can omit it in case every variable is on its own row. That means that it is OK to do the following.
let myVariable1 = 100
let myVariable2 = 200
But our code would fail to run if we would put the two lines mentioned above on the same line.
let myVariable1 = 100 let myVariable2 = 200
; between them. This is just hypothetically speaking because this is not something you would like to do normally as it makes the code less readable.
let myVariable1 = 100; let myVariable2 = 200;
We are going to look into how to create and print out a numeric variable.
Let’s open VS Code editor and get into it.
Click on “New file” inside VS Code.
Let’s save the file and give it a name. Press Cmd+S (for Mac) or Control+S (for Windows). Then select or create a folder where do you want to keep your code. I have created a folder “programming”. Then type the name of the file
variables.html. and click on the Save button.
A variable is something like a value holder we can give a name. Let’s say we would like to work with the age of a person called John in our code. We would want to create a variable named
johnAge that we would assign a number that equals John’s age. Let’s say John is 24 years old in the following code sample.
let johnAge = 24
Now we want to see what is John’s age in the web console, so we are going to print it out.
let johnAge = 24
Have a look at how to write and run the code described above.
Rules for creating variables
You do not need to put the code below into your code editor yet. Just have a look and try to remember what you can and cannot do.
Variables must be identified with unique names.
let a = 1
let b = 2
let a = 1
let a = 2
Variables can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
let x = 1
let age = 25
Names can contain letters, digits, underscores, and dollar signs.
let number1_000 = 1000
let _fancyVariable = 123
let $isCanDoThis = 14
let this will not work = 1
let this.will-not?work = 2
Names must begin with a letter
let number1 = 100
let 1number = 1
Names are case sensitive
For example, y and Y are different variables.
let y = 1
let Y = 2
let x = 2
let let = 1
Congrats, you have learned a lot today!
The next step is to learn how to work with variables. We are going to look at an example, so you will be able to decide, on your own, when you need to create a variable in your code.