Changing value of global variables in JavaScript


I'm doing a Javascript script and I find something I do not understand.

I have created a series of functions. Out of them I have declared (empty) some variables that I understand as being declared global and that will take the value of inside the functions. Later I will use the value of these variables.

The fact is that, through the console I can access the value of these variables but there are times when I return the value and others that undefined returns.

Surcharge the page returns me to undefined. If I leave the browser and re-launch the index.html it shows me the value correctly.

  function H(){
      var re = /\tH\s*((.*),\s*(.*))\(/gm; 
      if ((m = re.exec(resultados_texto)) !== null) {
        if (m.index === re.lastIndex) {
        // View your result using the m-variable.
        // eg m[0] etc.
        Hlatitud = m[2];
        Hlongitud = m[3];
        return (m[1])

I can only see the value of Haltitude if I previously called the function H ()

Until I call the function returns undefined

asked by kamome 22.02.2016 в 19:31

1 answer


What happens is that the inside of the function is not executed (it is only compiled to run later). Only when H () is executed are the internal lines of the function executed. To not see the undefined can be added above all:

Hlatitud = "valor inicial";
answered by 12.03.2016 в 00:39