How to add new value to an existing array in JavaScript?

JavascriptWeb DevelopmentFront End Technology

To add new value to an existing array, use the JavaScript splice() method.

Example

You can try to run the following code to add new value −

Live Demo

<html>
   <head>
      <title>JavaScript Array splice Method</title>
   </head>
   <body>
      <script>
         var arr = ["orange", "mango", "banana", "sugar", "tea"];
         document.write("Original array:"+arr)

         var newArr = arr.splice(2, 0, "water");
         document.write("<br>After adding new element: " + arr );
      </script>
   </body>
</html>

Output

Original array:orange,mango,banana,sugar,tea
After adding new element: orange,mango,water,banana,sugar,tea
raja
Updated on 18-Jun-2020 08:22:28

Advertisements