Access variable inside and outside a function

0

Is it possible to access a variable within a function out of it?

I would like to use a variable that was created in a function outside of it, but without returning it to return of the function.

In PHP we can do this

$variavel = 123;

function qualquerCoisa(){
    global $variavel;

    echo $variavel;
}

I want something similar in JavaScript

function qualquerCoisa(){
    var teste = 1;
}

qualquerCoisa();

console.log(teste); // <- Aqui, dá erro porque a variável está dentro da função.
    
asked by anonymous 22.02.2016 / 07:06

2 answers

4

In JavaScript the scope of the variables depends on the reserved word var . If a variable is created without this word it will be global, otherwise local.

Ex:

function setNome1(nome) {
  nome_usuario = nome; // nome_usuario foi criada no escopo global
}

function setNome2(nome) {
  var nome_usuario = nome; // nome_usuario foi criada no escopo local
}

setNome1('lucas');
alert(nome_usuario); // lucas
setNome2('felipe');
alert(nome_usuario); // lucas

In the same way that functions can create variables in the global scope, you can access them.

Ex:

var nome = 'matheus';
function getNome() {
    // A variável nome não existe neste escopo.
    // O interpretador irá buscar em no escopo do qual essa
    // função foi definida. Caso não exista, irá buscar no
    // escopo superior, e assim por diante.
    // Caso a variável não exista será lançado um erro
    // ReferenceError: nome is not defined
    //
    return nome; // 'matheus'
}

alert(getNome()); // 'matheus'

Any function can also change the value of a variable defined in the scope from which it was defined, or in the upper ones.

Ex:

var nome_usuario = 'douglas';
function setNome(nome) {
    nome_usuario = nome;
}

alert(nome_usuario); // douglas
setNome('emilia');
alert(nome_usuario); // emilia
    
22.02.2016 / 14:02
2

In PHP, to export the variable itself would have to declare it global. It's the only way. But do not do this . In general, global variables should only be used in PHP in very specific situations, and certainly not in order to export a variable.

/ p>

In several languages a global variable is somewhat bad given the size of the application. in PHP it is not so bad because it runs as script . Still, one must be careful. Even though it is not so problematic, there are better solutions and it is almost impossible to have a good justification for using a global variable for this case. Then look for a better solution.

If you just want to return the value, then a simple return will resolve. Eventually if you need to return more than one value there is the solution of using a parameter by reference or even returning a data structure with more than one value (an array , for example).

    
22.02.2016 / 19:00