While writing my own code, I messed up some of the declarations.
Still, sometimes I could reference variables correctly and sometimes I couldn't, so I looked into what was going on.
First, here is the basic behavior of each.
Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration). However, if a constant is an object or array its properties or items can be updated or removed. (MDN)
The let declaration declares a block-scoped local variable, optionally initializing it to a value. (MDN)
The var statement declares a function-scoped or globally-scoped variable, optionally initializing it to a value.(MDN)
now, basically we use the "const" and "let".
but if you need to understand older code, you have opportunity to read code by using "var".
What is the different on these words?
The strangest difference I noticed while writing the code is as follows
console.log(a); const a = 1; //ReferenceError
console.log(a); let a = 1; //ReferenceError
console.log(a); var a = 1; //undefined
Why is it only "undefined" when using "var"?
Because, var declaration are processed before some code is executed.
var declaration has two parts.
declaration and assignment.
declaration part is rolled up to the nearest function or global scope.
var a; console.log(a); //undefined var a = "value"; console.log(a); //"value"
Even if you only used const and let, you need to understand how var works.