[Demo] var and let difference in JavaScript

This example demonstrates what is difference between var and let keywords in JavaScript. What is scope of let and var.

by Rahul Saraswat

HTML

<!-- Please press ctrl-shift-i or right-click on browser to see output in browser console window. -->

JavaScript

//'let' introduced in ES6. Before ES6, we used to use 'var'
//let see the example with var first

for(var i=0;i<10;i++){
	console.log('\n' + i);
}
//See how 'i' is accessible outside of for loop, because scope of var keyword is upto nearest function
console.log('\n var keyword value: ' + i);	// will

for(let j=0;j<10;j++){
	console.log('\n' + j);
}
//'j' is not accessible outside of for loop, because scope of let keyword is upto nearest block
console.log('\n let keyword value: ' + j);		// will throw error 'j is not defined'

//Main difference is var & let is about scope. Scope of var keyword is anywhere inside nearest function, 
//but scope of let keyword is inside the nearest block only