0

I'm trying to get an array's length and display it on a page, like so:

var someArray = ['item 1', 'item 2', 'item 3'];

var getArrayLength = function() {
    return someArray.length;
}

getArrayLength();

For some reason this isn't working. I tried to replace the element's innerHTML, same issue.

<p id="demo"></p>
document.getElementById("demo").innerHTML = someArray.length;

Even if I set a variable equal to someArray.length and then return the variable it doesn't work. I don't get any errors, just no result. Is there something special about returning the length of an array in a function?

I was able to pull this off using jQuery, I'm just curious as to what I was doing wrong with the vanilla javascript.

4
  • 1
    What "doesn't work" exactly mean? "just no result" --- every expression in JS returns some result. Your provided code works just fine, try it yourself. Commented Feb 12, 2017 at 23:36
  • Probably not waiting for the page to load. Is your script before or after the p element? Commented Feb 12, 2017 at 23:39
  • Try logging with console.log(). If you get number, try using .innerText instead. Commented Feb 12, 2017 at 23:40
  • You call your function and then immediately discard its result. So what do you expect to see? Commented Feb 12, 2017 at 23:41

3 Answers 3

3

You don't even have to declare any functions.

var someArray = ['item 1', 'item 2', 'item 3'];

document.getElementById("demo").innerHTML = someArray.length;
<p id="demo"></p>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it turned out to be related to the order the page was loading.
1

You have to set the innerHTML (or textContent which is better) after the document is loaded. Try this:

window.addEventListener("load", function() {
    document.getElementById("demo").textContent = someArray.length;
});

jQuery code was working because it's internally waiting for the load event (assuming that you've wrapped your code inside $(function() {...})).

1 Comment

Thanks, the issue was with the document not being fully loaded.
1

actually your code is working but you are not actually trying to display anything. in your case add something actually giving you output.

var someArray = ['item 1', 'item 2', 'item 3'];

var getArrayLength = function() {
    return someArray.length;
}

console.log(getArrayLength());
alert(getArrayLength());

Comments

Your Answer

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