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.

let carId = 43; 

Now if we try to reference careIdbefore we declare it we get the error:

console.log(careId); // error!
let careId = 43; 

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.

console.log(carId); // undefined (not an error)
var carId = 43;

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.

if (true) {
    var foo = 9;
}
console.log(foo); // 9

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:

if (true) {
    let foo = 9;
}
console.log(foo); // error!

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:

console.log(carId);
var carId = 100;

Result: undefined

Now we use let insted of var:

console.log(carId);
let carId = 100;

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 (true) {
    let carId = 100;
}
console.log(carId);

If we use var keyword insted of let we get tha value: 100, for example:

if (true) {
    var carId = 100;
}
console.log(carId);

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 BuyMeACoffee