See variables as containers or a box, holding an information (data) inside it.
Variable declaration with let
Here a variable is declared by name ‘greetings’
A value can then be assign to the variable ‘greetings’ by using the assignment operator =
let greetings = 'Good day';
In order to access the string ‘Good day’ associated with the variable name ‘greetings’, the variable name need to be called:
let greetings = 'Good day'; alert(greetings) // output Good day in an alert or dialogue box
Alternatively, above statement could be split into two and still produce same results:
let greetings = 'Good day'; // greetings is declared and assign directly let greetings; greetings = 'Good day'; // greetings is declared and later assigned to the string value 'Good day' alert(greetings); // output same results
The format you choose to work with is entirely optional or based on team best pratices.
Variable declaration with const
In addition to let keyword, variables can also be declared using the keyword ‘const’ which stands for constant.
Const is used when a value is known and isn’t going to changed over time. Example: mathematical formulars, hard coded values or birth day date are values that can not be changed and can be declared with const keyword.
const BIRTHDAY = 05.11.1975;
Note that reassigning a constant value will throw an error. Once declared it can not be reassigned to a different value.
Variable declaration with Var
Var keyword is another way to declare a variable but that’s no longer in use and regareded as old school.
The difference between var and let is pretty negligible. The scope of var declaration is same as let.