First item returns undefined

1

I'm trying to print a split , but after passing for , the first value returns as undefined , could you tell me what it could be?

function parteTexto() {
  var teste;
  var texto = document.getElementById("caixa").value;
  var textoSplit = texto.split(" ");
  for (var i = 0, j = textoSplit.length; i < j; i++) {
    teste += textoSplit[i] + "<br/>"

  }
  document.getElementById("mostrar").innerHTML = teste;
}
<input id="caixa" type="text">
<button onclick="parteTexto()">Analisar</button>
<div id="mostrar"></div>
    
asked by anonymous 23.09.2017 / 04:28

2 answers

3

The value of teste is undefined initially, and when you concatenate with teste+= ... , this undefined is converted to string and concatenated with textoSplit[i] .

To resolve, start teste as empty string:

var teste = '';
    
23.09.2017 / 04:34
2

When you create a variable without starting it, the default value is:

undefined

If you want to confirm, open Google Chrome, enter the programmer console and test this Javascript command:

var x;console.log(x)

You will see that it will print exactly the undefined.

If you start it with an empty string "":

var x="VAZIO";console.log(x)

Empty is just an example of what's going to happen, obviously you'll replace the empty word with nothing, just two quotes.

    
23.09.2017 / 06:36