How to access, within a function, a global variable that has the same identifier as the variable within the function?

Asked

Viewed 85 times

3

Let’s assume I have the following Javascript code:

let variavel = 22
function funcao(){
  let variavel = 333
  console.log(variavel)
}
funcao() //333

We realized that, since the variable declared within the (local) function has the identifier equal to the global variable (declared outside the function), the one that has priority is the local.

However, I would like to access the global within the function if possible. How to do? In this case, I would like to print 22 instead of 333.

I know that, in the browser, variables var are attached to the object window, but this is not a variable var, also did not want to depend on the object window, as wanted can do the same on Node, for example.

  • Can’t send the variable as a function parameter and change its name? For example, you call the function with funcao(variavel) and receives with another name: function funcao(novavariavel){}... the value of variavel out of the function is now inside the function with the name novavariavel.

  • Yes, I could do that.. but I would like to know in the specific case shown in the msm code. If it is possible to do this etc.

1 answer

6


Using the same identifier is not possible as you block (shadow) access to the global variable by declaring an equal identifier within the function. The only output in this case is to declare the global with var and directly access the global object (window or global), as you yourself quoted.

But I would think twice before discarding the suggestion of Sam. It’s not usually a good idea that a function relies on global variables, it makes code harder to understand and maintain. Whenever you can, prefer to pass values as an argument.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.