Arrays are one of the most important data structures in JavaScript, allowing us to store and manage collections of data efficiently. But instead of just talking about arrays in an abstract way, let's make it relatable by using a real-world example: a family.
Imagine an array as a big family where each member has a specific position (index). Your family starts with a grandfather, grandmother, father, mother, elder brother, elder sister, and you.
let family = ["Grandfather", "Grandmother", "Father", "Mother", "Elder Brother", "Elder Sister", "Me"];
Now, letβs explore the 10 most commonly used JavaScript array methods with real-world family scenarios.
1. push()
- Adding a Newborn to the Family πΆ
When a new child is born, they are added at the end of the family.
family.push("Newborn Baby");
console.log(family);
Output:
["Grandfather", "Grandmother", "Father", "Mother", "Elder Brother", "Elder Sister", "Me", "Newborn Baby"]
2. pop()
- When a Member Passes Away βΉοΈ
If the youngest family member (last in the array) passes away, we remove them.
family.pop();
console.log(family);
Output:
["Grandfather", "Grandmother", "Father", "Mother", "Elder Brother", "Elder Sister", "Me"]
3. unshift()
- When Grandparents Move In π΄π΅
If grandparents move into the house, they are added at the beginning.
family.unshift("Great Grandfather", "Great Grandmother");
console.log(family);
Output:
["Great Grandfather", "Great Grandmother", "Grandfather", "Grandmother", "Father", "Mother", "Elder Brother", "Elder Sister", "Me"]
4. shift()
- When Great Grandparents Pass Away π’
If the great grandparents pass away, they are removed from the beginning.
family.shift();
family.shift();
console.log(family);
5. splice()
- When a Family Member Moves Away π
If the elder brother moves to another city, we remove him.
let index = family.indexOf("Elder Brother");
if (index !== -1) {
family.splice(index, 1);
}
console.log(family);
6. slice()
- Making a Guest List for a Family Function π
If you want to invite only the parents and siblings, you can extract that portion of the family.
let guestList = family.slice(2, 6);
console.log(guestList);
7. concat()
- When Two Families Merge π
If you get married, your spouse's family joins yours.
let spouseFamily = ["Father-in-law", "Mother-in-law", "Spouse"];
let combinedFamily = family.concat(spouseFamily);
console.log(combinedFamily);
8. indexOf()
- Checking If a Member Exists π
You want to check if "Mother" is in the family.
console.log(family.indexOf("Mother")); // Returns the index of "Mother"
9. includes()
- Confirming Membership β
If you want to check whether "Cousin" is part of your family.
console.log(family.includes("Cousin")); // false
10. join()
- Sending a Family Message π¨
You want to send a message with all family names separated by commas.
console.log(family.join(", "));
Top comments (0)