Pushing a variable on to an array results in TypeError: array.push is not a function

I spent a lot of time looking at it and I don’t see anything wrong, but the Erro message says otherwise.

In my code, I am trying to add the space string to the end of the string I enter as an argument to the pad function. The amount of times the space gets added is determined by the value contained in the num argument.

const pad = (string, num) => {
    let final = [string]; // supposed to be an array
    let space = '-';

    for (let i = 0; i < num; i++) {
      if (i === 0 && num % 2){
        final = final + space;
        num--;
      }
      final.push(space); // TypeError: final.push is not a function
    }
    return final.join('');
  };
  
  console.log(pad('Hi', 3));

Also, I know that there is a better way to accomplish the task, but I just can’t wrap my head around the Error message and what’s causing it.

You used the + operator to add space to the array final and assigned it back to final instead of using .push() so it’s no longer an array. What JavaScript is actually doing is using the array’s .toString() method then concatenating the space string, then assigning the result of that back to final.

Here’s some more sample code for you to consider:

const testArray = ['test1', 'test2'];
const testString = 'another test';

console.log(testArray);
// prints: [ 'test1', 'test2' ]

console.log(testArray.toString())
// prints: test1,test2

console.log(testArray + testString);
// prints: test1,test2another test

1 Like

Thank YOUU, I now feel relieved knowing what went wrong.

1 Like