UbuntuDude
UbuntuDude

Reputation: 39

Javascript - Display array elements

I am trying to run a simple Javascript to display the elements of an array that I create by splitting a string. The code is as follows:

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Loops</h1>

<p id="demo"></p>

<script>
  var text = "01/01/2016";
  var parts = text.split("/");
  var i;
  for (i = 0; i < parts.length; i++) {
    var x += parts[i] + "<br>";
  }
  document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

The above code does not display anything on the browser and I can't for the life of me figure out where the error is. Can someone advise?

Upvotes: 0

Views: 3488

Answers (4)

Adrianopolis
Adrianopolis

Reputation: 1292

Define x outside the for loop.

var text = "01/01/2016";
var parts = text.split("/");
var x = "";
for (i = 0; i < parts.length; i++) { 
    x = x + parts[i] + "<br>";
}
document.getElementById("demo").innerHTML = x;

Upvotes: 0

Selmaril
Selmaril

Reputation: 766

fgil give you good answer - you declare x variable in loop, at the first - it's not initialized (you have get error on += ), and second - you reset variable each iteration by declaring it at the loop. But I think that this loop is not needed. You can make code more simple and short if you will use method join of Array. Look at this:

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Loops</h1>

<p id="demo"></p>

<script>
  var text = "01/01/2016";
  var parts = text.split("/");
  var x = parts.join("<br>") + "<br>";
  document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Here fiddler with sample

You can do it in one line:

document.getElementById("demo").innerHTML = "01/01/2016".split("/").join("<br>") + "<br>";

Upvotes: 1

Andr&#233; Werlang
Andr&#233; Werlang

Reputation: 5944

This line is tricky, so any JavaScript compiler would complaint:

var x += parts[i] + "<br>";

Uncaught SyntaxError: Unexpected token +=

You can't declare a variable with the "+=" assignment operator.

Let's rewrite this assignment:

var x = x + parts[i] + "<br>";

When it works, the result is the same. Only that the first time this runs, x is undefined, not initialized yet. Concatenating undefined to any a string will contain the string undefined in the result.

But does it re-declare the variable? No, because a concept called hoisting, any variable declaration, even inside a loop, is pushed to the top of the scope, in this case the global scope. (We're not talking about let and const)

To solve that, before you read from this variable, you need to definitely assign to it, i.e. initialize.

var x = '';

Later you'll be able to use the operator +=, and then you don't need to use the var keyword.

Upvotes: 1

fgil
fgil

Reputation: 19

you are just failing in a basic concept. var x must be declared before the loop, like this:

var x = '';
for (i = 0; i < parts.length; i++) {
    x += parts[i] + "<br>";
}

Upvotes: 0

Related Questions