how to change the value of a variable that is out of all the functions in javascript?

1

** hello someone can help me I have a question as to how I can change the value of a variable that is outside all functions but only in a function I want to call it to change the value this is an example of what I want to do

var numero =1;
function cambiar(){
    numero= 2
}

function llamar(){
  numero= ...; //Aquí *
}

* here is where I want to call the variable again and have the value of the previous function.

    
asked by Care Papa Rh 15.03.2018 в 19:16
source

2 answers

4

The code as you have it written works correctly, since you declared the variable outside the functions, so it is a Global variable.

var numero =1;

cambiar();
llamar();//devuelve 2

function cambiar(){
  numero = 2;
}

function llamar(){
  console.log(numero);
}
    
answered by 15.03.2018 в 19:42
1

Since numero is a global variable:

  • you can simply invoke the cambiar function from where and when you want its value to change
  • you can use the variable from any field for the same reason, because it is global

For example here, let's test the variable numero within the function llamar() before it changes value and then:

var numero = 1;
llamar();

function cambiar() {
  numero = 2;
}

function llamar() {
  console.log("Antes del cambio: " + numero);
  cambiar();
  console.log("Después del cambio: " + numero);
}

Note that since the variable is global , if you use numero in the function llamar without invoking cambiar , the variable will have the value 1 , because it does not there has been change in it.

    
answered by 15.03.2018 в 19:25