Variables declared using var keyword scoped to the current execution context. This means If they are inside a function we only can access them inside the function. and If they are not they are part of the global scope which we can access anywhere. look at the example below to better understanding.
Here, Mango is scoped to function scope and Apple belongs to the global scope. If we try to access a global variable it is possible. but if we try to access a function scoped variable it is not possible. look at another example below.
One of the issues with using the var keyword is they can be redeclared inside the same scope. This will brings up some serious issues if we declare another variable using the same name inside the same scope, the new variable will replace the old one. var can be updated as well.
And another issue with var is these variables are not block-scoped which means if we have conditions statements those are not scoped to that statement but to the entire function or to the global scope.
This is the improved version of var declarations. Variables declaration using this way eliminates all the issues that we discussed earlier. let creates variables that are block-scoped. Also, they can not be redeclared and can be updated. The below example shows it is the best choice to use let than var.
Check out the below example to understand more about the behavior of let in the block scope.
Const variables are cannot be updated or redeclared. This way is used to declare constants. Same as the let declarations const declarations are block-scoped. Unlike var and let, If we are using const to declare a variable that must be initialized.
If we use const when object creating we can still update properties inside that object. Refer to the below example for better understanding.
I personally prefer to use let and const over var and use const to declare constant variables and always use let to declare variables if it is not a constant.