I have written three separate blogs each one describing thoroughly all 3 types of variable declarations. If you want to check the out before proceeding further:
|var can't create block scope||let/const creates block scope|
|var can be re-declared||let/const can't be re-declared|
|var declarations are hoisted and initialized with
||let/const declarations are hoisted but are not initialized|
|variable declared with let can be re-assigned.||const declarations can't be re-assigned.|
Yes, only if it is a reference type.
const declaration can't be assigned again that doesn't mean you can't change the existing value.
Take the example of assigning an array to a const declaration. We can't assign another array but we can change the value of the existing array because the reference is not changing.
const arr = [1,2,3]; arr.push(4); console.log(arr); //[1,2,3,4] const arr = [1,2,3]; arr = [4,5,6]; TypeError: Assignment to constant variable
let in such cases where array values will be changed in the future like in the above example to avoid the confusion created by the meaning of
You can use const anywhere if the values will not be changed in the future.
- In my current coding style I don't use
- I use
letwhere values can be changed in the future.
- I use
constfor cases where values will not be changed like imports, exports, constant values, etc.
If you want to wanna talk about tech and F.R.I.E.N.D.S we can connect on Twitter.