Day 1: Simple Types
Lesson 7: let vs var
In JavaScript there are actually two ways to declare a variable: let
and var
.
You will see both across examples and documentation around the internet. The differences are subtle but important and it comes down to something called scope.
In programming scope is incredibly important and determines where certain bits of data can be accessed from. This will become clearer later on as you move through this course but I want to seed this in you mind here.
If we think about your code like a house, we can get a good analogy for how code is divided up.
In the kitchen is a cooker, you can only use and access the cooker in the kitchen. So the cooker is scoped to the kitchen.
The house has an Amazon Echo with really great microphones, from anywhere in your house you can say "Hey, Alexa" and it will here you. From the perspective of your house, Alexa has global scope.
Let's look at some code:
Oooo-kay, let's break this down. Think about the whole code window as your house, this is global scope. Think about the lines between the { }
as your kitchen, it has it's local scope.
So global
is declared at the top and is available everywhere, just like Alexa. You see both times it is console.log
ed out it prints.
local
is declared between the { }
so can only be referenced within that that scope. Which is why we see it printed the first time but not at the end (the code has actually crashed, you just can't see that with this little play ground).
BUT, varName
is declared within the { }
and is accessible in both places. That's because var
breaks the local scope of your { }
and declares it globally. Not a big deal in a program of this size but when once you code project gets bigger its easy to accidentally reuse names, when they are declared with var
this causes errors that you can avoid by using let
.