Since I've been getting back into working with JavaScript, there have been a few cases where I've had to quickly google to confirm something I probably should have already known. One of these things, is the difference between var, let and const in JavaScript.
We can declare variables in three ways in JavaScript:
var age = 28;
let height = 188;
const weight = 190;
But where would we use each one? Short version, in terms of updating:
- If we want to update and/or re-declare the value, use var
- If you want to update but not re-declare the value, you may use let
- If you don't want to update the value, use const
And in terms of scope:
- If you want to restrict the scope to either a function, or globally, use var
- If you want to restrict the scope to a block (anything between two curly braces, i.e. for loops, if statements), use let or const
A quick example to sum up all these scenarios? Let's give it a go:
function sharePersonalDetails() {
var age = 28;
let height = 188;
const weight = 200;
if(age > 25)
{
let iq = 100;
let height = 210;
console.log(age); // Outputs: 28
console.log(iq); // Outputs: 100
console.log(height); // Outputs: 210
console.log(weight); // Outputs: 200
}
// Age should always be in scope
console.log(age); // Outputs: 28
// Iq however, is no longer in scope, as a let
console.log(iq); // ReferenceError: iq is not defined
// Whereas height is in scope! But it's the original one
// The height within the if block is a separate variable to the original
console.log(height); // Outputs: 188
// We can declare age again, as it's a var
var age = 30;
// But we can't declare height again, as it's a let
let height = 190; // Uncaught SyntaxError: Identifier 'height' has already been declared"
// BUT, we can still reassign it
height = 190;
console.log(height); // Outputs: 190
// And, being a const, this was never going to work
weight = 185; // TypeError: Assignment to constant variable.
console.log(weight); // Outputs: 200
}
There are a couple of different scenarios to consider, but this code block is normally enough to remind me why the developer has used let in one instance, and var in another.