• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Miscellaneous / How To Insert An Item Into An Array Using JavaScript

How To Insert An Item Into An Array Using JavaScript

How To Insert An Item Into An Array Using JavaScript

Inserting an item into an array in JavaScript is a simple task that can be accomplished using a few different methods. In this article, we will explore three different ways to insert an item into an array in JavaScript, including using the push() method, the splice() method, and the concat() method.

The push() method is one of the most commonly used methods for inserting an item into an array. This method adds one or more items to the end of an array and returns the new length of the array. The syntax for using the push() method is as follows:

array.push(item1, item2, ...);

For example, if we have an array called colors and we want to insert the color “purple” at the end of the array, we would use the following code:

colors.push("purple");

The splice() method is another method that can be used to insert an item into an array. This method allows you to add or remove items from an array at a specific index. The syntax for using the splice() method is as follows:

array.splice(index, 0, item);

For example, if we have an array called numbers and we want to insert the number 4 at the second index of the array, we would use the following code:

numbers.splice(1, 0, 4);

The concat() method is a third method that can be used to insert an item into an array. This method combines two or more arrays into a new array. The syntax for using the concat() method is as follows:

newArray = array1.concat(array2, array3, ...);

For example, if we have an array called fruits and we want to insert the array ["bananas", "oranges"] at the end of the fruits array, we would use the following code:

fruits = fruits.concat(["bananas", "oranges"]);

Miscellaneous

Related Snippets:

  • Remove duplicate items from an array
  • Replace a portion of a string with something else
  • Check if an Item Exists in an Array
  • Convert a string into an array

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers