Let and var for variable declarations
Let
and var
keyword for variable declarations, those two allows you to declare variables. Let see the difference.
Here we declare a variable called: careId
using: let
keyword and assigning 43
.
Now if we try to reference careId
before 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 C/C++
or Java
programming languages. That’s one of the reasons that let
keyword is preferred over var
.
Another difference between let
and 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 9
. But let
works in a different way. Below is our block we use let
instead of var
:
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.
Example:
Result: undefined
Now we use let
insted of var
:
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 let
over var
. If we create a block we use a let
keyword to assigned 100
to 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.
My site is free of ads and trackers. Was this post helpful to you? Why not
Disqus is great for comments/feedback but I had no idea it came with these gaudy ads.