0

I am new to JavaScript, I am trying to write a simple function to print array elements using while statement, but I am getting an extra undefined value at the end. Any help will be highly appreciated

Codes are:

var a = [1, 3, 6, 78, 87];

function printArray(a) {

    if (a.length == 0) {
        document.write("the array is empty");
    } else {
        var i = 0;
        do {
            document.write("the " + i + "element of the array is " + a[i] + "</br>");

        }
        while (++i < a.length);
    }
}

document.write(printArray(a) + "</br>");

and the output is:

the 0element of the array is 1
the 1element of the array is 3
the 2element of the array is 6
the 3element of the array is 78
the 4element of the array is 87
undefined

How I am getting the undefined value? Am I skipping any index? Thanks in advance!

James Taylor
  • 5,468
  • 6
  • 42
  • 62
N Das
  • 3
  • 2

2 Answers2

3

The reason this is happening is because your printArray function is not returning any value, which means it is actually returning undefined

You could fix this in two ways:

  1. Change document.write(printArray(a) + "</br>"); to printArray(a);document.write("<br/>")]
  2. Make your printArray return a string instead of doing document.write and keep your other code

Second way is more recommended and also note that using document.write is not recommended either, try setting document.body.innerHTML or something like that

Would recommend reading these for future reference as well:

Array.forEach

Why is document.write a bad practice

Community
  • 1
  • 1
juvian
  • 15,212
  • 2
  • 30
  • 35
0
var a = [1, 3, 6, 78, 87];

function myFunction() {
    var i = 0;
    while (i < a.length) {
        document.write("the " + i + "element of the array is " + a[i] + "</br>");
        i++;
    }
}
Parth Raval
  • 3,325
  • 2
  • 20
  • 30