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
βœ«π•½π–†π–Œπ–Šπ–— ✫
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β€’10mo 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β€’10mo ago
No description
clevermissfox
clevermissfoxβ€’10mo ago
Maybe in strict mode it would throw that error? Or if its a const
glutonium
glutoniumβ€’10mo ago
ig.. what if u wanna access da global variable here idk how u can do dat from within da function
glutonium
glutoniumβ€’10mo ago
this kind of works
No description
βœ«π•½π–†π–Œπ–Šπ–— ✫
Yeah... something like this
glutonium
glutoniumβ€’10mo ago
great
cat
catOPβ€’10mo 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β€’10mo 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β€’10mo 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β€’10mo 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β€’10mo ago
oh thanks
Want results from more Discord servers?
Add your server