Before es6 javascript have tow scope global and functional scope, not block scope. Means let consider snippet below
function demo(){
a= 1;
var b = 2;
console.log(a,b);//1,2
}
console.log(a,b);//1, undefined
because a is consider as global scope of demo(), note this happen because of hosting and scope of b is within function. Now if you declare variable 'a' again then it will rewrite(scope of a is global).
function demo(){
a= 1;
var b = 2;
console.log(a,b);//1,2
}
var a = 2;
console.log(a,b);//2, undefined
if we write code like
{ var a = 10; } console.log(a);// 10 it means that a is not in the scope of {} this block means we don't have block scope.
Now when let is introduce then JavaScript have the capability of block scope. Because let prevent the default JavaScript behavior of hosting. Like
{
let a = 10;
console.log(a);//10
}
console.log(a);// a is not declare error
==>>Now consider your code first snippet
const cloudCount = () => {
let i = 2;
console.log(i); // 2
for (let i = 0; i < 10; i++) {
console.log(i);
// All numbers from 0 to 9
} };
here the scope of first 'i' is according to the code is global means anybody can use and scope of second 'i' is within loop, so here first 'i' and second 'i' is different and we can declare same variable multiple time in different scope. That is why no error.
==>>Now consider your code second snippet
const cloudCount = () => {
let i = 2;
console.log(i); // 2
for (var i = 0; i < 10; i++) {
console.log(i);
// All numbers from 0 to 9
} };
here first 'i' was no problem to run, when come to var i and we know var does't have block scope it should be either global and function and for is not a function so that JavaScript try to host the variable 'i' means "put on the top". When JavaScript try to do this then it find that already variable is declare within a block scope(let). And let prevent to declare same variable multiple time in same scope. For that it gives error.
And when we write code like
const cloudCount = () => {
var i = 2; console.log(i); // 2
for (var i = 0; i < 10; i++) {
console.log(i); // All numbers from 0 to 9
} };
When var used to declare then if same variable is already present in same scope then it will rewrite again no problem. Means when second 'i' is declare with var then it will host and rewrite with first 'i' variable.