0

I keep getting undefined before my output text in JS. Here is my code.

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Learning javascript</title>
</head>
<body>

    <p id="arrayString"></p>



    <!-- Javascript -->
    <script type="text/javascript" src="JS/app2.js"></script>
</body>
</html>

This is my JS

var arrayString;
var myArray=["Ms.Vickies", "Old Dutch", "Lays"];
for (var i=0; i<myArray.length; i++) {
    arrayString=arrayString+myArray[i];
}
document.getElementById("arrayString").innerHTML=arrayString;

my output is undefinedMs.VickiesOld DutchLays

In addition why no spaces? I am new to JS but am working my way up. Cannot figure this out.

1
  • To allow people to easily help you, consider making a jsfiddle of your problem. jsfiddle is a site where you can run javascript with html live in the browser. Commented Jan 7, 2015 at 14:04

3 Answers 3

7

It's because in your first loop iteration, arrayString is undefined. Set it equal to an empty string instead.

Instead of declaring arrayString like so:

var arrayString;

Initialize it with an empty string:

var arrayString = '';
Sign up to request clarification or add additional context in comments.

Comments

1

Because you are initiating a null/undefined variable by doing this: var arrayString;

You can fix it by doing this: var arrayString = "";

Better yet, instead of using a for loop, you can do it like this:

var myArray=["Ms.Vickies", "Old Dutch", "Lays"];
document.getElementById("arrayString").innerHTML = myArray.join(" ");

More info: http://www.w3schools.com/jsref/jsref_join.asp

Comments

0

In code ,you have just declared,not initialized.so,just replace

  var arrayString;

with

 var arrayString = '';

Hope it helps...Thank you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.