Variables
Variables in JavaScript are declared using one of three keywords: let, const, or var.
let allows you to declare block-level variables. The declared variable is available from the block it is enclosed in.
let a;
let name = "Simon";
// myLetVariable is *not* visible out here
for (let myLetVariable = 0; myLetVariable < 5; myLetVariable++) {
// myLetVariable is only visible in here
}
// myLetVariable is *not* visible out here
const allows you to declare variables whose values are never intended to change. The variable is available from the block it is declared in.
const Pi = 3.14; // Declare variable Pi
console.log(Pi); // 3.14
A variable declared with const cannot be reassigned.
const Pi = 3.14;
Pi = 1; // will throw an error because you cannot change a constant variable.
const declarations only prevent reassignments — they don't prevent mutations of the variable's value, if it's an object.
const obj = {};
obj.a = 1; // no error
console.log(obj); // { a: 1 }
var declarations can have surprising behaviors (for example, they are not block-scoped), and they are discouraged in modern JavaScript code.
If you declare a variable without assigning any value to it, its value is undefined. You can't declare a const variable without an initializer, because you can't change it later anyway.
let and const declared variables still occupy the entire scope they are defined in, and are in a region known as the temporal dead zone before the actual line of declaration. This has some interesting interactions with variable shadowing, which don't occur in other languages.
function foo(x, condition) {
if (condition) {
console.log(x);
const x = 2;
console.log(x);
}
}
foo(1, true);
In most other languages, this would log "1" and "2", because before the const x = 2 line, x should still refer to the parameter x in the upper scope. In JavaScript, because each declaration occupies the entire scope, this would throw an error on the first console.log: "Cannot access 'x' before initialization". For more information, see the reference page of let.
JavaScript is dynamically typed. Types (as described in the previous section) are only associated with values, but not with variables. For let-declared variables, you can always change its type through reassignment.
let a = 1;
a = "foo";