Adding an element at the start of the array in Javascript

JavascriptWeb DevelopmentFront End Technology

In this article, we are going to learn how to add an element at the start of the array in JavaScript.

An array is a special variable, which can hold more than one value sequentially. It is a collection of items stored at contiguous memory locations. The idea is to store multiple items together. This makes it easier to calculate the position of each element by simply adding an offset to a base value of the memory location of the first element of the array. The base value is index 0 for the first element in the array and the difference between the two indexes is the offset.

Syntax

Following is the syntax for the array data structure in JavaScript.

const array = ["Value1", "Value2", "Value3"];

Arrays allow random access to elements. This makes accessing elements by position faster and easy. Arrays have better cache locality which makes a pretty big difference in performance. Arrays represent multiple data items of the same type using a single name, instead of storing different items in different variables.

Adding Array Elementsat the Beginning

We use unshift() function to add an element. The function adds the element at the start of an array.

Syntax

Following is the syntax for the adding an element at the start of the array in JavaScript.

array.unshift(item)

Example

Following is the example program for adding an element at the start of the array in JavaScript.

<!DOCTYPE HTML> <html> <head> </head> <body> <script > const arr1 = [0,1,2,3,4,5] arr1.unshift(6) document.write(arr1) </script> </body> </html>

We can add all type of data to the array.

Example

Following is the example program for adding an element at the start of the array in JavaScript.

<!DOCTYPE HTML> <html> <head> </head> <body> <script > const arr1 = ['Java', 'JavaScript', 'Node.js']; arr1.unshift("HTML") document.write(arr1) </script> </body> </html>

Example

Following is the example program for adding an element at the start of the array in JavaScript.

<!DOCTYPE HTML> <html> <head> </head> <body> <script > const arr1 = [0, 1, 2, 3, 4, 5] const arr2 = [6, 7, 8, 9, 10]; const concatedArray = arr1.concat(arr2); concatedArray.unshift('Hi i added first') document.write(JSON.stringify(concatedArray)); </script> </body> </html>
raja
Updated on 21-Nov-2022 11:09:37

Advertisements