0

I'm trying to return an array from a function and work with its results.

When I just want to get its length, I always get a 0:

function myFunc() {
  var arr = [];

  arr.push("test");
  arr.push("another test");

  return arr;
}

alert(myFunc.length) // expected 2, but got 0

Here is a fiddle.

1
  • 5
    alert(myFunc().length) Commented Apr 20, 2016 at 12:43

4 Answers 4

6

You need to call it as myfunc().length because you are calling a function.

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

Comments

3

Remember you are calling a function, so the parameter list (even if empty) must be given to the call, try:

alert(myFunc().length)

Comments

1

You have to call the function like so

function myFunc() {
  var arr = [];

  arr.push("test");
  arr.push("another test");

  return arr;
}

alert(myFunc().length)

https://jsfiddle.net/n5xdcrzm/

Comments

0

Function.length, The length property specifies the number of arguments expected by the function.

And that is the reason you could get 0 in alert as you are reading length property of the function-object

If you are expecting 2, which is length of the array, you need to invoke the function.

function myFunc returns the array in which 2 items are being pushed.

Invoke the function and read the length property of the returned array

function myFunc() {
  var arr = [];
  arr.push("test");
  arr.push("another test");
  return arr;
}

alert(myFunc().length);

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.