Var and Let in Javascript

Bynayakdillip

Var and Let in Javascript

Var and Let in Javascript

Var:-Dynamic data type in javascript
let:-dynamic data type in javscript

Difference between Var and Let
The difference is “let” is visible only in the for() loop and var is visible to the whole function.

when you use Let

<script>
var iPLTemsList = ['CSK', 'DD', 'KXIP', 'KKR','MI','RCB','SRH','RR'];
for(let ipl in iPLTemsList){
  alert(iPLTemsList[ipl]);
}
alert(ipl);
</script>

//JavaScript error: Uncaught ReferenceError: ipl is not defined on line 6

when you use var

<script>
var iPLTemsList = ['CSK', 'DD', 'KXIP', 'KKR','MI','RCB','SRH','RR'];
for(Var ipl in iPLTemsList){
  alert(iPLTemsList[ipl]);
}
alert(ipl);//Display 7
</script>

Also, If you Redeclaration var and let, var will let you re-declare the same variable in the same scope. On the other hand, let will not:

'use strict';
let i= 3;
let i = 5; // SyntaxError: Identifier 'i' has already been declared
'use strict';
var i = 3;
var i = 5; // No problem, `i` is replaced.

Advantages of using let over var within a function. the difference is that let is block-scoped and var is not.

Note:-Experts always recommend solely using let everywhere, if it is available in your environment.

About the author

nayakdillip administrator

Leave a Reply