As it turns out I’ve been doing everything wrong. Well, maybe not everything, but at the very
There are actually three different variable types in JavaScript, var, let, and const. I’ve been using var exclusively and it’s actually bad practice. So what’s the difference between each and which should I be using when?
const
Where at all possible you should use const. Unsurprisingly const is short for constant and without going into to much detail that means it’s something you know will not change. You won’t be able to use this all the time obviously because a lot of the time you need to vary the content of variables. It’s always good
let
This is how most of your variables should be declared the majority of the time. The strength of let variables is their scope is limited to the block level. For example:
let numberOfPowers = 1;
if (numberOfPowers === 1) {
let numberOfPowers = "1 more power than Batman"
console.log(numberOfPowers);
}
console.log(numberOfPowers);
In this example we have two variables named the same thing, but because we are using let their scope is limited to different parts of the code so they don’t collide. So in the console, we’d see both “1” and “1 more power than Batman”.
var
This is the option you should use least often and that’s because of its scope. Unlike let, var has a very wide scope. This is either the function it’s inside of, or if it’s declared outside any function, global. Obviously, that’s not ideal because it creates a greater opportunity to have your variables collide, especially as your projects grow in size. So to revisit our example with var instead of let:
var numberOfPowers = 1;
if (numberOfPowers === 1) {
var numberOfPowers = "1 more power than Batman"
console.log(numberOfPowers);
}
console.log(numberOfPowers);
This time the console will only read 2x “1 more power than Batman”. This is because having a global scope means we are writing over a single global variable rather than creating two different variables with different scopes but the same name.
I can see when you’re learning why this concept might be more of an intermediate level concept. Scope can be a bit tricky to get your head around. At the early stages of learning it’s probably better to focus on core concepts rather than nuances like this, but as your skills grow I think this is an important practice to do with variable declaration.