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.
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
Maybe in strict mode it would throw that error? Or if its a const
ig.. what if u wanna access da global variable here
idk how u can do dat from within da function
this kind of works
Yeah... something like this
great
sorry i had to dip after posting the question
let me read the msgs
i didnt get itπ
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)
ohh
now i get it
and is the address of both the variable gonna be same?
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)
oh
thanks