find() helper

listening to britney spears on September 13th, 2021

Find() is a great little helper that is used to find specific items in a list. With a for loop, along with an if statement, the code looks something like this:

js
let family = [
{name:'Jennifer'},
{name:'Ana'},
];
let familyMember;
for(let x=0; x < family.length; x++ ) {
if(family[x].name === 'Ana') {
familyMember = family[x];
}
}
console.log(familyMember);
// ^ displays {name:'Ana'} in console

The for loop iterates through all the names on the list until it finds a family member with the name Ana. Using the find() helper, there is less logic to write out. There is no need to write an if statement within a loop, just return the family member with the matching name:

js
let family = [
{name:'Jennifer'},
{name:'Ana'},
];
let test = family.find(function(familyMember) {
return familyMember.name === 'Ana';
})
console.log(test);
// ^ displays {name:'Ana'} in console

I really encourage all devs out there to move to es6 helpers. It keeps the js files clean and eligible. Have you ever opened a js file with 1000 lines of code and 20 for loops? CAUSE IT HAPPENS, and it's out there in someones production codebase....


view all posts