JavaScript arrays are dynamic, so elements can be added without specifying the array size beforehand.
- Use methods such as push() and unshift() to add elements at the end or beginning.
- Use an index or splice() to insert elements at a specific position.
- Use spread or concat() when you want to create a new array without modifying the original.
Approach 1: Using Array Index
An element can be added dynamically at a specific index by directly assigning a value to that index.
var a = ['Hi', 'There'];
a[3] = 'Geeks';
console.log(a[3]);
console.log(a[2]);
Output
Geeks undefined
Approach 2: Using push() Method
The push() method adds one or more elements to the end of an array.
var a = [];
a.push('Geeks');
a.push('For');
a.push('Geeks');
console.log(a);
Output
[ 'Geeks', 'For', 'Geeks' ]
Approach 3: Using unshift() Method
The unshift() method adds one or more elements to the beginning of an array.
var a = [];
a.unshift('Geeks');
a.unshift('For');
a.unshift('Geeks');
console.log(a);
Output
[ 'Geeks', 'For', 'Geeks' ]
Approach 4: Using splice() Method
The splice() method can add elements at a specific position without removing existing elements.
Syntax:
Array.splice(index, remove_count, item_list)Example:
const language = ['HTML', 'Css'];
language.splice(
language.length,
0,
'Javascript',
'React'
);
console.log(language);
Output
[ 'HTML', 'Css', 'Javascript', 'React' ]
Approach 5: Using Spread Operator
The spread operator (...) can create a new array by combining the existing elements with new elements.
// JavaScript Array Initialization
let a = ['Hi', 'There'];
// New element added dynamically using spread operator
a = [...a, 'Geeks'];
console.log(a); // Output: ['Hi', 'There', 'Geeks']
Output
[ 'Hi', 'There', 'Geeks' ]
Approach 6: Using concat() Method
The concat() method combines an existing array with one or more values or arrays and returns a new array.
let a = ['Hi', 'There'];
a = a.concat(['Geeks', 'For', 'Geeks']);
console.log(a);
Output
[ 'Hi', 'There', 'Geeks', 'For', 'Geeks' ]
Approach 7: Using map() Method
The map() method can be combined with other array methods when elements need to be transformed or added based on specific logic.
let array = [1, 2, 3];
const addToArray = (arr, newElement) => {
return arr.map(item => item).concat(newElement);
};
array = addToArray(array, 4);
console.log(array);
Output
[ 1, 2, 3, 4 ]