The variable “var” was since the beginning of JavaScript i.e. since 1997. So, if someone didn’t updated there browser since the beginning(or past 10 years) the keyword “var” will only work on there browser.
The variables "let” and “const” were introduced recently in ES6(In 2015). There were some design mistakes made with “var” and these were rectified with “let” and “const”.
The problem is that “var” is FUNCTION scoped and it causes a lot of problems.
Consider the below example where we are USING “var” inside a traditional “for” loop. But we are also able to access and update “i” outside of the “for” loop.
Since, “var” is function scope so we can put our “for” loop inside a function and then “i” won’t be accessible outside.
function incrementI() { for(var i=0; i<5; i++) { console.log(i); } } incrementI(); //Output- 0 1 2 3 4i = i + 2; console.log(i);//Output-
/* Exception: ReferenceError: i is not defined @Scratchpad/6:9:1 */Traditional languages like C, C++ and Java as they are blocked scope and it is what was desired from JavaScript. So, the variable “let” and “const” introduced in 2015 were made block scoped.
The “for” loop declared with “let” will also throw an error, when we try to access “i” outside of it. It is because the scope of “i” ends with the “for” loop.
for(let i=0; i<5; i++) { console.log(i); //Output- 0 1 2 3 4 } i = i + 2; console.log(i);//Output-
/* Exception: ReferenceError: i is not defined @Scratchpad/6:6:1 */We will understand “const” now. It is similar to “let” and have block scope. But it was created to declare constant variables in JavaScript. We cannot assign a new value to a variable after the initial declaration for primitive types like INTEGERS and strings.
const c = 12; c = 14; console.log('c is ', c);/*
Exception: TYPEERROR: invalid assignment to const `c'
@Scratchpad/6:2:1
*/
But can add or update values for non-primitive like arrays and objects.
const arr = [1, 2, 3]; arr.push(4); console.log('arr is ', arr); // [ 1, 2, 3, 4 ] const obj = { name: 'Robin', skill: 'JS' }; obj.skill = 'React'; obj.profession = 'Developer'; console.log('obj is ', obj); // { name: "Robin", skill: "React", profession: "Developer" }
Write Your Comments or Explanations to Help Others