Behavior of "var", "let", and "const" used in variable declarations in Javascript
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.
const
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)
let
The let declaration declares a block-scoped local variable, optionally initializing it to a value. (MDN)
var
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
const.js
console.log(a);
const a = 1; //ReferenceError
let.js
console.log(a);
let a = 1; //ReferenceError
var.js
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.
sample.js
var a;
console.log(a); //undefined
var a = "value";
console.log(a); //"value"
Conclusion
Even if you only used const and let, you need to understand how var works.
Thank you.
Top comments (0)