1. Naming Variables
2. Creating Variables
3. Chaining variables
Variables are the heart and soul of any programming language. As the name implies, they are able to vary data, and therefore the first step in making your program dynamic.
Variables are containers for storing data values.
What does that mean? It means you can invent your own variable names, and assign a value to them. From that moment on, you can access this variable by its name from anywhere inside the program, and retrieve its value.
Unlike some programming languages, a variable’s data type is not fixed. For instance, if I create a variable as a Number, I can change it to a String or Boolean later without problems.
Names must start with a letter, underscore ( _ ) or dollar ( $ ) sign. After that, you’re allowed to use any letters, numbers or special characters. You’re not allowed to use white space.
It’s common practice to make your variables descriptive, so you know exactly what they mean, but not too long. It’s also preferred to write them in camelCase, which means you only use lowercase letters, but the first letter of each new word within the variable is uppercase. This improves readability, while remaining quick to type.
A lot of people write their global variables in UPPERCASE, which I think is a good thing to do, but you can employ your own favourite notation.
Variables are created with the
var keyword, followed by the name you want to give it.
You can stop right there if you want, but you can also assign its value at the same time by using
var someVariable = "Fantastico!";
Now, any time you want, you can access its value just by using its name.
var someVariable = true; console.log(someVariable); //Prints true to the console
And if you want to change it, you simply assign a new value!
var someVariable = "Fantastico!"; someVariable = 10;
Often, it’s cleaner to declare all your (global) variables at once at the top of your document. To quickly declare variables, you can place the names after each other, separated by a comma.
var someVar, anotherOne, andLastOne;
It’s also possible to assign the same value to multiple variables at once, by chaining them together with equal-signs between them:
var someVariable, anotherOne, andLastOne; someVariable = anotherOne = andLastOne = null;
If you want to store a certain value, but not allow it to change, you can create a constant. If you try to change it, or declare a variable with the same name, the program will throw a big error. Therefore, the only way to create them is by using the
const keyword, and immediately assigning the value.
const PI = 3.14;