Skip to content
the poor coder

how to add in array

Poor Man
Published
Reading time
2 min read
On this page

How to add in array?#

Adding elements to an array is a fundamental operation in JavaScript programming. You can add elements to an array using different methods. Let's take a look at some of them:

Method 1: Using the push() method#

The push() method adds one or more elements to the end of an array and returns the new length of the array. Here's an example:

Text

let myArray = [1, 2, 3];
myArray.push(4);
console.log(myArray); // Output: [1, 2, 3, 4]

Method 2: Using the unshift() method#

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array. Here's an example:

Text

let myArray = [1, 2, 3];
myArray.unshift(0);
console.log(myArray); // Output: [0, 1, 2, 3]

Method 3: Using the splice() method#

The splice() method can add, remove, or replace elements in an array. To add elements using splice(), you need to specify the index position where you want to start adding elements, the number of elements you want to remove (which is 0 in this case), and the new elements to be added. Here's an example:

Text

let myArray = [1, 2, 3];
myArray.splice(1, 0, 4);
console.log(myArray); // Output: [1, 4, 2, 3]

Method 4: Concatenating arrays#

You can also add elements to an array by concatenating it with another array. This method creates a new array that contains the elements of both arrays. Here's an example:

Text

let myArray1 = [1, 2];
let myArray2 = [3, 4];
let myNewArray = myArray1.concat(myArray2);
console.log(myNewArray); // Output: [1, 2, 3, 4]

These are some of the ways to add elements to an array in JavaScript. Choose the method that best fits your needs and enjoy coding!

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC