Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Adding an element at the start of the array in Javascript
In JavaScript, adding an element at the start of an array is a common operation. The most straightforward method is using the unshift() method, which adds one or more elements to the beginning of an array and returns the new length.
An array is a data structure that stores multiple values in a single variable. Arrays in JavaScript are zero-indexed, meaning the first element is at position 0.
Syntax
array.unshift(element1, element2, ..., elementN)
Parameters
The unshift() method accepts one or more parameters representing the elements to add at the beginning of the array.
Return Value
The method returns the new length of the array after adding the elements.
Using unshift() with Numbers
<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
const arr1 = [0, 1, 2, 3, 4, 5];
console.log("Original array:", arr1);
const newLength = arr1.unshift(6);
console.log("Array after unshift:", arr1);
console.log("New length:", newLength);
document.write("Modified array: " + arr1.join(", "));
</script>
</body>
</html>
Modified array: 6, 0, 1, 2, 3, 4, 5
Using unshift() with Strings
<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
const languages = ['Java', 'JavaScript', 'Node.js'];
console.log("Before:", languages);
languages.unshift("HTML");
console.log("After:", languages);
document.write("Languages: " + languages.join(", "));
</script>
</body>
</html>
Languages: HTML, Java, JavaScript, Node.js
Adding Multiple Elements
<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
const numbers = [3, 4, 5];
console.log("Original:", numbers);
numbers.unshift(0, 1, 2);
console.log("After adding multiple:", numbers);
document.write("Result: [" + numbers.join(", ") + "]");
</script>
</body>
</html>
Result: [0, 1, 2, 3, 4, 5]
Working with Complex Data
<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
const arr1 = [0, 1, 2, 3, 4, 5];
const arr2 = [6, 7, 8, 9, 10];
const concatenatedArray = arr1.concat(arr2);
concatenatedArray.unshift('First Element');
document.write("Final array: " + JSON.stringify(concatenatedArray));
</script>
</body>
</html>
Final array: ["First Element",0,1,2,3,4,5,6,7,8,9,10]
Key Points
- The
unshift()method modifies the original array - It returns the new length of the array
- Multiple elements can be added in a single call
- Elements are added in the order they appear in the parameter list
Conclusion
The unshift() method is the standard way to add elements at the beginning of an array in JavaScript. It's efficient and can handle multiple elements at once, making it perfect for prepending data to arrays.
