JavaScript arrays are dynamic, meaning that their size is not fixed and can change during runtime. You can add or remove elements from an array without having to declare its size beginning itself.
Here's an explanation with examples
1. Adding Elements to an Array
We can add values to a JS(JavaScript) array using methods like push()
, unshift()
, or by directly assigning a value to an index.
let arr = [1, 2, 3]; // Initial array with 3 elements
console.log(arr); // Output: [1, 2, 3]
arr.push(4); // Add an element to the end
console.log(arr); // Output: [1, 2, 3, 4]
arr[5] = 6; // Add an element at a specific index (index 4 will be empty)
console.log(arr); // Output: [1, 2, 3, 4, undefined, 6]
2.Removing Elements from an Array
let arr = [1, 2, 3, 4, 5];
console.log(arr); // Output: [1, 2, 3, 4, 5]
arr.pop(); // Remove the last element
console.log(arr); // Output: [1, 2, 3, 4]
arr.splice(1, 2); // Remove 2 elements starting from index 1
console.log(arr); // Output: [1, 4]
3. Length Property
The length property of an array updates automatically as elements are added or removed.
4.Sparse Arrays
If you assign a value to an index that's larger than the current length, the array becomes sparse, meaning it will have "empty" with undefined
values between the defined elements.
const value = [1, 2, 3, 4];
value[8] = 11; // Assign a value at index 8
console.log(value); //[ 1, 2, 3, 4, <4 undefined items>, 11 ]
console.log(value.length); //9
console.log(value[5]) // ?? try it
Sparse Arrays explained in YouTube video you can check it here
Let me ask you a question based on JS array understanding
What will be the console.log(value[5]) take above code block as question try it in your favorite code editor.
Summary
JavaScript arrays are flexible and can expand or shrink in size as needed. You can add or remove elements dynamically, and the array's length property will automatically adjust to reflect the current size. This dynamic nature makes JavaScript arrays very powerful for handling collections of data.