A variable is a container for a value, such as a string or a number we might use in a statement or as part of a sum.
var name = “Andrew”;
The current method of declaring variables, let, has a number of benefits over var.
For instance, var permits re-declaration of variables with the same name, whereas let generates an error.
It is recommended to use let instead of var, when declaring variables.
name is the name of the variable
After creating the variable, we can initialise it with a value:
name = 'Tom';
The equal sign (
=) is used to assign a value to our variable.
We can also assign our variable a value during creation, like this:
let name = 'Tom'; let age = 34;
Remember, that we need to enclose text values in quotes.
After initialising a variable, we can output its value, using a method called console.log:
let name = 'Tom'; console.log(name);
Variables can change their value during the program.
let age = 34; age = 24; console.log(age);
Updating the value of a variable can be done as many times as needed.
The const keyword was introduced in ES6 (2015). Constants are similar to variables and are declared using the const keyword:
const color = 'green'; console.log(color);
Constants must have a value when declared and they cannot change their value.
Constants are very useful. If you use const, it tells anyone looking at your code that this name will never be assigned to a different value.
Things to note about Constants:
- Variables defined with const cannot be Redeclared
- Variables defined with const cannot be Reassigned
- Variables defined with const have Block Scope