Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu April 07, 2023 › #append #Array

How to add one more value in array using JavaScript

In this article, you will learn how to append something to an array in JavaScript using the push() method, unshift() method and concat() method.

To add a single value to the end of an array in JavaScript, you can use the push() method. For example, if you have an array called myArray and you want to add the value '4' to the end of the array, you can use the following code.

<script>
 let myArray = [1, 2, 3];
 myArray.push(4);
 console.log(myArray) //output : [1, 2, 3, 4]
</script>

If you want to add a single value to the beginning of an array, you can use the unshift() method instead. Here's an example.

<script>
 let myArray = [1, 2, 3];
 myArray.unshift(4);
 console.log(myArray) //output : [4, 1, 2, 3]
</script>

You should remember that the push() and unshift() methods modify the original array. If you want to create a new array that includes the original values plus the new value, you can use the concat() method or the spread (...) operator.

<script>
 let myArray = [1, 2, 3];
 myArray = myArray.concat(4);
 console.log(myArray) output : [1, 2, 3, 4]
</script>
save
listen
AI Answer
Write Your Answer
loading
back
View All