var keyword for variable declarations, those two allows you to declare variables. Let see the difference.
Here we declare a variable called:
let keyword and assigning
Now if we try to reference
careIdbefore we declare it we get the error:
And that makes total sense. The program run from top to bottom and we try to use a variable that is not declared yet.
But if we declare:
carId using the
var keyword and try to access
carId we do not get an error.
This is very strange behaviour for people who came from
Java programming languages. That’s one of the reasons that
let keyword is preferred over
Another difference between
var has to do with scope.
In the code above we declare the variable
foo and initialise it to
9. But the outside the block we reference
foo. This is ok, we get the value
let works in a different way. Below is our block we use
let instead of
So the variable
foo will only exist in that code block,
let has block scoping. Once program execution will live this block the variable
foo no longer exists. When we try to log it out, we get an error. There is very important to keep in mind that
let has block scoping and
var does not.
Now we use
let insted of
After running this code, we get an error:
ReferenceError: carId id not defined. This is a preferred behaviour when we choose variable before is declared we want to error to be thrown. That’s why is to best practice to use
var. If we create a block we use a
let keyword to assigned
carId, we get:
ReferenceError: carId is not defined. Variable
carId only exists in the
if block. For example:
If we use
var keyword insted of
let we get tha value:
100, for example:
Let let’s catch errors earlier because the compiler will complain when there is a problem with the code. Your code is also easier to read.