javascript functions

if i declare a variable with the name "xyz" globally ( outside a function ) and give it a value... and then i declare another variable with the same name "xyz" inside a function and give it a different value.. then m i editing the original variable or im declaring a completely different variable?
13 Replies
Collins
Collins•2y ago
You're declaring a completely different variable. When you declare a variable with the same name both globally and inside a function, you're essentially declaring two separate variables that happen to have the same name. The variable inside the function is scoped to that function and is separate from the global variable. So, if you assign a different value to "xyz" inside the function, it will only affect the local variable within that function and not the global one. They are distinct variables with their own values.
glutonium
glutonium•2y ago
i think it is not even possible if u have declared a variable with name x in global scope.. i dont think u can declare it anywhere else. at least I think so 😂 but lemme try ig k ya nvm 😂 i thought it was gonna give error saying u r redeclaring variables.. which i think it should tho
glutonium
glutonium•2y ago
No description
curiousmissfox
curiousmissfox•2y ago
Maybe in strict mode it would throw that error? Or if its a const
glutonium
glutonium•2y ago
ig.. what if u wanna access da global variable here idk how u can do dat from within da function
glutonium
glutonium•2y ago
this kind of works
No description
Collins
Collins•2y ago
Yeah... something like this
glutonium
glutonium•2y ago
great
cat
catOP•2y ago
sorry i had to dip after posting the question let me read the msgs i didnt get it😭
Rägnar O'ock
Rägnar O'ock•2y ago
You can redeclare the same variable as long as you are not in the same scope as the original variable. That's called shadowing and you should avoid it as much as possible because it makes things hard to understand. A let/const is accessible from anywhere between the {} it was declared in (function, class, if, static block... Anything as long as you have curly braces) . If you declare a new let/const in a sub scope of the one you created the first variable it will hide the original (shadowing it)
cat
catOP•2y ago
ohh now i get it and is the address of both the variable gonna be same?
Rägnar O'ock
Rägnar O'ock•2y ago
Nope, they are 2 totally distinct variables. And because they have the same name you can only read/write to the one declared in the lowest scope (that's why shadowing should be avoided)
cat
catOP•2y ago
oh thanks

Did you find this page helpful?