Evgenij Reznik
Evgenij Reznik

Reputation: 18594

Work with returned array from function

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.

Upvotes: 0

Views: 70

Answers (4)

Rayon
Rayon

Reputation: 36609

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);

Upvotes: 0

KieranDotCo
KieranDotCo

Reputation: 467

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/

Upvotes: 1

Arturo Montaño
Arturo Montaño

Reputation: 121

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

alert(myFunc().length)

Upvotes: 3

Imesha Sudasingha
Imesha Sudasingha

Reputation: 3570

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

Upvotes: 6

Related Questions