In this article, we will be talking about 2 different array properties.
Let's start with the most common array property.
1. Array Length
The length property is used to set or return the length of an array. The length of an array is always 1 greater than the last index of that array. The length of the array automatically updates when we modify the array.
const arr = [1, 2, "nedy", undefined, null, true];
// syntax for returning ther length of an array
arr.length // 6
The length property also allows us to modify the size of an array by setting its length. This can be done initializing the length of the array to any numerical value.
const arr = [1, 2, "nedy", undefined, null, true]; // length = 6
// Decreasing the size of the array.
arr.length = 4; // length = 4
console.log(arr.length, arr); // 4 [1, 2, "nedy", undefined]
const arr1 = [1, 2]; // length = 2
// Increasing the sie of the array
arr1.length = 5; // length = 5
console.log(arr1.length, arr1); // 5 [1, 2, undefined, undefined, undefined]
N/B: The length of the array is always one greater than the last index of the array.
const players = ['messi', 'ronaldo', 'nedy'];
players[1000] = "Ashley y";
console.log(players.length) // 1001
2. Array Prototype
This gives us the ability to add new properties and methods to our array object. All arrays then created will be given these properties and methods on default.
// initializing an `initialz` property
Array.prototype.initialz = function() {
for (let i = 0; i < this.length; i+=1) {
this[i] = this[i].charAt(0).toUpperCase();
}
};
let name ="nedy udombat"
name = name.split(" ")
// since name is an array we can call the initialz() on it
name.initialz();
console.log(name)
Here we created an array method that extracts the initials of a person's name and stores it in an array.
After declaring and initializing the name
variable by doing this let name ="nedy udombat"
, we call the split()
method on it, to split it and return an array.
Array.split()
is an array method that splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split. You can read more about it here.
Conclusion
The array length property is used to set or return the length of an array while the array prototype property is used in adding new properties or methods to the array object.
Here is the link to the other articles on this Array series written by me:
Got any question, addition or correction? Please leave a comment.
Thank you for reading. 👍
Top comments (1)
Great. Now I know I know nothing.