Add new object to array javascript

A simple one!

In JavaScript, you can add a new object to an array using the following methods:

  1. Using the push() method:

    const myArray = [];
    myArray.push({ name: 'John', age: 30 });
    console.log(myArray); // Output: [{ name: 'John', age: 30 }]

    The push() method adds the new object to the end of the array.

  2. Using the concat() method:

    const myArray = [];
    myArray = myArray.concat([{ name: 'John', age: 30 }]);
    console.log(myArray); // Output: [{ name: 'John', age: 30 }]

    The concat() method returns a new array with the new object added to the end of the original array.

  3. Using the splice() method:

    const myArray = [];
    myArray.splice(myArray.length, 0, { name: 'John', age: 30 });
    console.log(myArray); // Output: [{ name: 'John', age: 30 }]

    The splice() method inserts the new object at the specified index (in this case, the end of the array).

  4. Using the unshift() method:

    const myArray = [];
    myArray.unshift({ name: 'John', age: 30 });
    console.log(myArray); // Output: [{ name: 'John', age: 30 }]

    The unshift() method adds the new object to the beginning of the array.

All of these methods will add a new object to the array. Choose the one that best fits your use case!