First item returns Undefined

Asked

Viewed 83 times

1

I’m trying to print on inner one split, however, after passing through the for, the first value returns as undefined, could tell me what it might 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>

2 answers

3

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

To resolve, initialize teste as empty string:

var teste = '';
  • Thank you! That’s right!

2

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

undefined

If you want to confirm, open Google Chrome, log in to 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 will happen, obviously you will replace the empty word with nothing, just two quotes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.