Jon Snow
07 April 2023
Mainly used on Strings, but can be useful when working with Arrays of primitive types
const results = ["Won", "Lost", "Won"];
Old
const hasLost = results.indexOf("Lost") > -1;
New
const hasLost = results.includes("Lost");
Very similar to includes, but it allows you to check if an internal property meets a condition
const users = [
{ name: "Ted", experience: 5 },
{ name: "Bill", experience: 10 },
];
Old
const hasExperience = users.filter((u) => u.experience > 5).length > 0;
New
const hasExperience = users.some((u) => u.experience > 5);
Useful if you need to check if all items meet a condition, before we used to use the filter method
const results = ["Lost", "Lost", "Lost"];
Old
const hasLosingStreak = results.filter((r) => r === "Lost").length;
New
const hasLosingStreak = results.every((r) => r === "Lost");
Useful when you only need to find one item in an array, no filter is required these days
const users = [
{ name: "Ted", experience: 5 },
{ name: "Bill", experience: 10 },
];
Old
const ted = users.filter((u) => u.name === "Ted")[0];
New
const ted = users.find((u = u.name === "Ted"));
In the past we had to use for loops to find the index of an item, not anymore with this method
const users = [
{
name: "Ted",
experience: 5,
},
{
name: "Bill",
experience: 10,
},
];
Old
let indexOfTed;
for (let [index, user] of users) {
if (user.name === "Ted") {
indexOfTed = index;
break;
}
}
New
const indexOfTed = users.findIndex((u) => u.name === "Ted");
Useful if you need to add an item to the top of an Array, before we had to use the splice method
const fruits = ["Banana", "Cherry"];
Old
Fruits.splice(0, "Apple");
New
fruits.unshift("Apple");
Useful if you need to remove the last item in an Array, it will also return that item if you need it
const fruits = ["Apple", "Potato"];
Old
fruits.splice(fruits.length - 1, 1);
New
fruits.pop();
Check if a variable is of type Array with this handy method, the old way was a bit weird lol
const books = ["📗", "📕", "📘"];
Old
Object.prototype.toString.call(books) === "[object Array]";
New
Array.isArray(books);