Skip to content Skip to sidebar Skip to footer

Why Do I Get ".push Not A Function"?

What's wrong with my code? I keep on getting 'outPut.push is not a function'.

Solution 1:

Array push functions returns the length of the array after pushing.

So, in your code

outPut = outPut.push(strarr[counter + j]);

outPut is now a number, not an array, so the second time through the loop, outPut no longer has a push method.

A simple solution is to change that line to

outPut.push(strarr[counter + j]);

Solution 2:

Array.push

adds one or more elements to the end of an array and returns the new length of the array.

And you have this line:

outPut = outPut.push(strarr[counter + j]);

You're adding an element to outPut.push(strarr[counter + j]); and then reassigning outPush to the length of the array.

You should only call the push method on the array and a new element will be added:

for (var j = 0; j < k; j ++){
    outPut.push(strarr[counter + j]);
}

Solution 3:

Array.push() returns the length of that particular array. In your code, you assign a number to outPut. Now when the loop runs for the second time, outPut is no more an array but a number, hence you get the error.

You check it by logging outPut to the console. You will see that

for (var j = 0; j < k; j ++){
    outPut = outPut.push(strarr[counter + j]);
    console.log(outPut);
}

It will show:

1
  VM696:18 Uncaught TypeError: outPut.push is not a functionatlongestConsec (<anonymous>:18:21)
    at <anonymous>:1:1

All you need to do is change it to:

for (var j = 0; j < k; j ++){
    outPut.push(strarr[counter + j]);
}

Post a Comment for "Why Do I Get ".push Not A Function"?"