Add An Item To The Beginning Of An Array In JavaScript Or Node.js

Arrays are a commonly used data structure in JavaScript. When interacting with arrays, you likely want to manipulate them by adding new items. In some situations, you may want to add items to the beginning of an array.

This tutorial shows you three ways on how to prepend items to an array.

Node.js Series Overview

  • Node.js
  • Strings
  • Streams
  • Date & Time
  • Arrays
  • Promises
  • JSON
  • Iterators
  • Classes
  • Numbers
  • Objects
  • File System
  • Map
  • Process
  • Symbols
  • Platform/OS
  • HTTPS
  • Hashing
  • CLI
  1. Increase the Memory Limit for Your Process

  2. Why You Should Add “node” in Your Travis Config

  3. Retrieve a Request’s IP Address in Node.js

  4. How to Base64 Encode/Decode a Value in Node.js

  5. How to Fix “Uncaught SyntaxError: Cannot use import statement outside a module”

  6. Nested Destructuring in JavaScript or Node.js

  7. ESM Bypass Cache for Dynamic Imports

  8. String Replace All Appearances

  9. Generate a Random ID or String in Node.js or JavaScript

  10. Remove Numbers From a String in JavaScript or Node.js

  11. Get the Part After a Character in a String in JavaScript or Node.js

  12. Check If a String Includes All Strings in JavaScript/Node.js/TypeScript

  13. Limit and Truncate a String to a Given Length in JavaScript and Node.js

  14. How to Generage a UUID in Node.js

  15. Split a String into a List of Lines in JavaScript or Node.js

  16. Detect if a String is in camelCase Format in Javascript or Node.js

  17. Check If a String is in Uppercase in JavaScript or Node.js

  18. Get the Part Before First Occurrence in a String in JavaScript or Node.js

  19. Get the Part After Last Occurrence in a String in JavaScript or Node.js

  20. How to Shuffle the Characters of a String in JavaScript or Node.js

  21. Check if a String is Empty in JavaScript or Node.js

  22. Left-Trim Characters Off a String in JavaScript or Node.js

  23. Lowercase the First Character of a String in JavaScript or Node.js

  24. Prepend Characters or Words to a String in JavaScript or Node.js

  25. Convert a String to Buffer

  26. How to Implement a Custom `toString` Method

  27. How to Check if a Value is a ULID

Prev | Next
  1. String Replace All Appearances
  2. Remove All Whitespace From a String in JavaScript
  3. Generate a Random ID or String in Node.js or JavaScript
  4. Remove Extra Spaces From a String in JavaScript or Node.js
  5. Remove Numbers From a String in JavaScript or Node.js
  6. Get the Part Before a Character in a String in JavaScript or Node.js
  7. Get the Part After a Character in a String in JavaScript or Node.js
  8. How to Check if a Value is a String in JavaScript or Node.js
  9. Check If a String Includes All Strings in JavaScript/Node.js/TypeScript
  10. Check if a Value is a String in JavaScript and Node.js
  11. Limit and Truncate a String to a Given Length in JavaScript and Node.js
  12. Split a String into a List of Characters in JavaScript and Node.js
  13. How to Generage a UUID in Node.js
  14. Reverse a String in JavaScript or Node.js
  15. Split a String into a List of Lines in JavaScript or Node.js
  16. Split a String into a List of Words in JavaScript or Node.js
  17. Detect if a String is in camelCase Format in Javascript or Node.js
  18. Check If a String Is in Lowercase in JavaScript or Node.js
  19. Check If a String is in Uppercase in JavaScript or Node.js
  20. Get the Part After First Occurrence in a String in JavaScript or Node.js
  21. Get the Part Before First Occurrence in a String in JavaScript or Node.js
  22. Get the Part Before Last Occurrence in a String in JavaScript or Node.js
  23. Get the Part After Last Occurrence in a String in JavaScript or Node.js
  24. How to Count Words in a File
  25. How to Shuffle the Characters of a String in JavaScript or Node.js
  26. Append Characters or Words to a String in JavaScript or Node.js
  27. Check if a String is Empty in JavaScript or Node.js
  28. Ensure a String Ends with a Given Character in JavaScript or Node.js
  29. Left-Trim Characters Off a String in JavaScript or Node.js
  30. Right-Trim Characters Off a String in JavaScript or Node.js
  31. Lowercase the First Character of a String in JavaScript or Node.js
  32. Uppercase the First Character of a String in JavaScript or Node.js
  33. Prepend Characters or Words to a String in JavaScript or Node.js
  34. Check if a String is a Number
  35. Convert a String to Buffer
  36. Prevent Line Breaks in String Template Literals
  37. How to Implement a Custom `toString` Method
  38. What Is `Symbol.toStringTag` and How to Use It
  39. How to Check if a Value is a ULID
  1. Get Number of Seconds Since Epoch in JavaScript

  2. Increase a Date in JavaScript by One Week

  3. Add Month(s) to a Date in JavaScript or Node.js

  4. Get the Current Year in JavaScript or Node.js

  5. How to Convert a UNIX Timestamp to a Date in JavaScript or Node.js

  6. Get Yesterday's Date in JavaScript or Node.js

  7. Add Hours to a Date in JavaScript or Node.js

  8. Check If a Date is Tomorrow in JavaScript or Node.js

  9. How to Format a Date YYYY-MM-DD in JavaScript or Node.js

  10. Get Number of Days in a Month

  11. How to Reset and Empty an Array

  12. Clone/Copy an Array in JavaScript and Node.js

  13. Sort an Array of Integers in JavaScript and Node.js

  14. Check If an Array Contains a Given Value in JavaScript or Node.js

  15. Append an Item at the End of an Array in JavaScript or Node.js

  16. Split an Array Into Smaller Array Chunks in JavaScript and Node.js

  17. How to Exit, Stop, or Break an Array#forEach Loop in JavaScript or Node.js

  18. How to Reverse an Array in JavaScript and Node.js

  19. Sort an Array of Objects in JavaScript, TypeScript or Node.js

  20. Join an Array of Strings to a Single String Value

  21. Run Async Functions/Promises in Sequence

  22. Run Async Functions in Batches

  23. Detect if Value Is a Promise in Node.js and JavaScript

  24. Thenables and Creating Your Own Promises

Prev | Next
  1. Callback and Promise Support in your Node.js Modules
  2. Run Async Functions/Promises in Sequence
  3. Run Async Functions/Promises in Parallel
  4. Run Async Functions in Batches
  5. How to Fix “Promise resolver undefined is not a function” in Node.js or JavaScript
  6. Detect if Value Is a Promise in Node.js and JavaScript
  7. Overview of Promise-Based APIs in Node.js
  8. Thenables and Creating Your Own Promises
  1. Write a JSON Object to a File

  2. Securely Parse JSON

  3. Check If a Value Is Iterable in JavaScript or Node.js

  4. What is `Symbol.iterator`?

  5. Retrieve the Class Name at Runtime in JavaScript and Node.js

  6. Deprecate a Method in JavaScript and TypeScript

Prev | Next
  1. Extend Multiple Classes (Multi Inheritance)
  2. Retrieve the Class Name at Runtime in JavaScript and Node.js
  3. Deprecate a Method in JavaScript and TypeScript
  1. Ensure a Positive Number in JavaScript or Node.js

  2. Check If a Number has Decimal Places in JavaScript or Node.js

  3. Convert Boolean to Number

  4. Check if a Value is a Number

Prev | Next
  1. Generate a Random Number in Range With JavaScript/Node.js
  2. Ensure a Positive Number in JavaScript or Node.js
  3. Check if a Number Is Infinity
  4. Check If a Number has Decimal Places in JavaScript or Node.js
  5. Use Numeric Separators for Better Readability
  6. Convert Boolean to Number
  7. Convert Number to Boolean
  8. Check if a Value is a Number
  1. How to Check if an Object is Empty in JavaScript or Node.js

  2. How to Snake_Case Keys of an Object in JavaScript or Node.js

  3. How to Get All Keys (Including Symbols) from an Object in JavaScript or Node.js

  4. Iterate Through an Object’s Keys and Values in JavaScript or Node.js

  5. Check If a Value Is an Object in JavaScript or Node.js

  6. How to Lowercase Keys of an Object in JavaScript or Node.js

  7. Get a File’s Created Date

  8. How to Create an Empty File

  9. How to Rename a File

  10. Check If a Path Is a File

  11. How to Touch a File

  12. Check If a Directory Is Empty

  13. Get a File‘s Extension

  14. Get a File Name (With or Without Extension)

  15. Delete a File From Disk

  16. Check if a Path is a Socket

  17. Check if a Path is a File URL

  18. What is `Fs.realpath`?

Prev | Next
  1. Get a File’s Created Date
  2. Get a File’s Last Modified or Updated Date of a File
  3. How to Create an Empty File
  4. Check If a Path or File Exists
  5. How to Rename a File
  6. Check If a Path Is a Directory
  7. Check If a Path Is a File
  8. Retrieve the Path to the User’s Home Directory
  9. How to Touch a File
  10. Read File Content as String
  11. Check If a Directory Is Empty
  12. How to Create a Directory (and Parents If Needed)
  13. Get a File‘s Extension
  14. Get the Size of a File
  15. Get a File Name (With or Without Extension)
  16. Read a JSON File
  17. Delete a File From Disk
  18. Check if a Path is a SymLink (Symbolic Link)
  19. Check if a Path is a Socket
  20. Check if a Path is a FIFO File (Named Pipe)
  21. Check if a Path is a File URL
  22. Handling `fs.Stats` Constructor is Deprecated
  23. What is `Fs.realpath`?
  1. Transform to an Object

Prev | Next
  1. Create From Object
  2. Transform to an Object
  1. Show Your NODE_MODULE_VERSION

Prev | Next
  1. Determine the Node.js Version Running Your Script
  2. Show Your NODE_MODULE_VERSION
  1. Detect if Running on Linux

  2. Detect if Running on Windows

  3. Constant for Platform-Specific Newline

  4. Retrieve the OS Directory for Temporary Files

Prev | Next
  1. Detect if Running on Linux
  2. Detect if Running on macOS
  3. Detect if Running on Windows
  4. Check if Running on 64bit or 32bit Platform
  5. Constant for Platform-Specific Newline
  6. Determine the Current Operating System
  7. Retrieve the OS Directory for Temporary Files
  1. Strict Type for Request Headers with TypeScript

Prev | Next
  1. How to Download a File
  2. Strict Type for Request Headers with TypeScript
  1. Retrieve the List of Supported Hash Algorithms

  2. Calculate a SHA512 Hash

Prev | Next
  1. Calculate an MD5 Hash
  2. Retrieve the List of Supported Hash Algorithms
  3. Calculate a SHA256 Hash
  4. Calculate a SHA512 Hash
  1. Using the Styletext Utility for Terminal Text Formatting

Prev | Next
  1. Using the Styletext Utility for Terminal Text Formatting

3 Ways Adding Items to the Beginning of a JavaScript Array

JavaScript supports different ways of adding items to the beginning of an array. You can use the native Array#unshift method, create a new array in combination with spreading existing items into the new array or create a new array by concatenating two arrays.

Prepend Items to an Existing Array

The Array#unshift method adds one or more items to the beginning of an array.

Notice: Array#unshift returns the new length of the array, not the array containing the new item(s):

const ids = [1, 2] const newArrayLength = ids.unshift(3) // 3 // the value of "ids" is [3, 1, 2] ids.unshift(4) // the value of "ids" is [4, 3, 1, 2] // or prepend multiple values ids.unshift(5, 6, 7) // the value of "ids" is [5, 6, 7, 4, 3, 1, 2]

Add and Spread Items Into a New Array

You can also create a new array and add the new items at the beginning. This is a short and concise way in combination with the spread operator to add the values of an existing array:

const ids = [1, 2, 3] const newIds = [4, ...ids] // [4, 1, 2, 3] const newIds = [4, 5, 6, ...ids] // [4, 5, 6, 1, 2, 3]

Concat(enate) Arrays Items

You may also create a new array of the items you want to prepend to the existing array. Then, concatenate the existing items to the end of the new array. This keeps the new items in the front and appends the existing ones to the end:

const ids = [1, 2, 3] const newIds = [4, 5, 6].concat(ids) // the value of "newIds" is [4, 5, 6, 1, 2, 3]

All three ways allow you to prepend one or more items to the beginning of an array. Enjoy!

What Should You Use?

Well, use what you like best!

I prefer Array#concat when building an array pipeline by chaining further operations, like Array#map, Array#filter, or Array#find.

In situations where I only want to prepend the item without additional operations, I’m using the spread operator.

In terms of performance: I don’t really care about performance optimizations on my side. I’m relying on the JavaScript runtime to optimize the code for me. This gives me the freedom of writing the code I like to read 😃

Tag » Add Element Array Js