Need to declare variables in a Javascript function



  • Hi. I'm starting to learn programming logic. When I will create a Javascript function, I declare and ask to return its value.

         function exemplo(teste){
                  var saida = teste + 4;
                  return saida;
         }
    

    Well, when I'm going to use the function, I'm declaring the exit again.

    var teste = parseInt(prompt('Diga um número.'));          
    var saida = exemplo(teste);
    alert(saida);
    

    If I ask to return the value said, why do I have to declare the variable again?



  • You don't have to declare again. You can do this:

    alert(exemplo(teste))
    

    However, if you need to use this result in more than one place, it is indicated to save the return in the variable. This way, you won't need to call the method again every time that value is needed.

    The fact of power does not mean that it is more indicated. Even using this return once, you can choose to save the return in the variable so that the code is cleaner.

    This way:

    var saida = exemplo(teste);
    alert(saida);
    

    It is more readable than that:

    alert(exemplo(teste))
    

    Likewise, you could do this:

    alert(exemplo(parseInt(prompt('Diga um número.'))))
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2