+ 1
Confusion about redeclaring with let keyword.
When I declare a variable with let it should not allow me to re declare it as said in course. But I've confusion in this code. Confusion explained with comments. https://code.sololearn.com/W674Hr36V862/?ref=app
5 ответов
+ 2
let v1 = 10;
function checking(){
if (true){
//here let v1 is inside if() block scope which means let variable inside block scope not available outside
let v1 = 5;
console.log(v1); //log 5
}
//this will log 10 becuz v1 is log inside function scope and due to lexical scope any variable outside function scope or global variable is available inside the function
console.log(v1);
//10}
checking();
//re declaring here returned error, uncomment line 17 to know error message.
//let v1 = 20;
console.log(v1); //log 10 cuz v1 which is in the global scope
+ 2
if you want to know more about visit youtube - techsith function scope
+ 1
I'm not an expert in JavaScript, but as no one else has responded, I'll offer my thoughts. 'let' has only a limited scope. Where you redeclare it in your 'if' block, that variable is only defined within that block. That's why it has a different value outside the block than inside.
In general, variables defined inside a function are considered separately from variables defined outside of that function. You can get the value of a variable defined outside (as your code shows), but if you redefine a variable with the same name within a function, it is considered a different variable. Even if you change your 'let's to 'var's, your variable is still the same outside the function after redeclaring it inside.
+ 1
let v1 = 10;// here v1 in the window so v1 at all the page is 10
function checking(){
// here still 10
if (true){
//re declaring same variable decalred by let did not return any error
let v1 = 5;
// here we changed to 5
console.log(v1); // here is 5
}
// because the let it will be 10 again
console.log(v1);
}
checking();
//re declaring here returned error, uncomment line 17 to know error message.
//let v1 = 20;
//let v1=10 here too
console.log(v1);
+ 1
Oh 😁
Because you re-declare it inside the { ... }