How to Insert an Element into an Array in javaScript?

23-Jun-2023

.

Admin

How to Insert an Element into an Array in javaScript?

This article is focused on javascript push() array – add element. I explained simply about array into array. We will use how to add to an array with the push. you will learn unshift. Let's get started with and concat functions.

There are several ways to insert an element into an array in JavaScript:

Example 1: Using the push() method: This method adds one or more elements to the end of an array.


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Insert an Element into an Array in javaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

let myArray = [1, 2, 3];

myArray.push(4);

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

</script>

</html>

Example 2: Using the unshift() method: This method adds one or more elements to the beginning of an array.

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Insert an Element into an Array in javaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

let myArray = [1, 2, 3];

myArray.unshift(0);

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

</script>

</html>

Example 3: Using the splice() method: This method can be used to add or remove elements from an array at a specified index.

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Insert an Element into an Array in javaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

let myArray = [1, 2, 3];

myArray.splice(1, 0, 'a', 'b');

console.log(myArray); // Output: [1, 'a', 'b', 2, 3]

</script>

</html>

In this example, we are adding two elements ('a' and 'b') at index position 1 (after the first element).

Note: The first argument of splice() is the index where you want to start adding or removing elements. The second argument is the number of elements you want to remove (in this case we don't want to remove any). The third argument and onwards are the elements you want to add.

#JavaScript