Published: 2nd of November 2021
There are 3 different keywords that can be used to define a variable.
- var - Depricated, should not be used for ES6+.
- let - Variable can be re-assigned. Value can be mutated.
- const - Variable cannot be re-assigned. Value can be mutated.
let and const have been available since ES6/2015.
Define a Variable
// var syntax (considered depricated) var name = "stuff"; // let syntax // initialize variable without value assignment // only available with "let" keyword let name; // initialize a variable and assign a value let name = "stuff"; // re-assign a variable let name = "things"; // const syntax // initialize a constant and assign a value // a value must be assigned when initialized const name = "stuff"; // re-assigning a constant will result in a runtime error const name = "things"; // => Uncaught SyntaxError: redeclaration of var name
- camelCase is the convention used for multi-word variables.
- Variables can contain letters, numbers, underscores _ and a dollar sign $.
- Variables cannot start with a number.
- let should be used when a variable may be overwritten such as in a for loop.
- const should be used when a variable should not be overwritten.