Difference between var, let and const keywords in javascript
Before ES6 there was only one way to declare the variables in Javascript using var. but there are issues associated with variables declared with var.
1. Scope: Scope essentially means where it can be used. or the lifetime of a variable.
a. var has a function-level scope. If we declare a variable inside the function using var it can applicable anywhere inside that function.
To understand further, look at the example below.
b. let has block-level scope. If we declare a variable inside the block(if, loop, etc) using let it can only be applicable inside that block.
c. const has block-level scope. similar to let scope.
2. Hoisting: Hoisting suggests that variable and function declarations are physically moved to the top of your code, reference from MDN.
a. var: var variables are hoisted to the top of its scope.
b. let: let variables do not support hoisting. let is preferred for variable declaration first and then usage.
c. const: same as let.
3. Re-declaration and Shadowing
a. var: var variable can be declared with the same name.
b. let: let variable can’t be declared with the same name.
c. const: const variable can’t be declared with the same name.
4. Reassigned
a. var: var variable can be reassigned with a different value.
b. let: let variable can be reassigned with a different value.
c. const: const variable can’t be reassigned with a different value.
Summary:
Got any questions or addition? please leave a comment.
Thank you for reading :)
Difference between var, let and const keywords in javascript video
https://www.youtube.com/watch?v=EN46IPqDNng
Please subscribe my youtube channel for tech videos
https://www.youtube.com/channel/UCQkvNcHN5vg3jEoeOb9Tdrw
Follow my page for the latest updates
Facebook: https://www.facebook.com/6Question
LinkedIn: https://www.linkedin.com/company/6Questions