DEV Community 👩‍💻👨‍💻

Cover image for JavaScript Array find() Method
Francisco  Inoque
Francisco Inoque

Posted on

JavaScript Array find() Method

The find () method returns the value of the first element of the array that satisfies the test function provided. Otherwise, the undefined value is returned.

const users = [
    {
        user_id: '1234',
        first_name: 'Francisco',
        last_name: 'Inoque',
        email: 'jaimeinoque20@gmail.com',
        username: '@franciscoinoque'
    },

    {
        user_id: '5678',
        first_name: 'Jose',
        last_name: 'David',
        email: 'josedavid@gmail.com',
        username: '@josedavid'
    },

    {
        user_id: '9101',
        first_name: 'Peter',
        last_name: 'Jordan',
        email: 'peterjordan@gmail.com',
        username: '@peterjordan'
    },

    {
        user_id: '1112',
        first_name: 'Clifton',
        last_name: 'Urik',
        email: 'cliftonurik@gmail.com',
        username: '@cliftonurik'
    }
]

let error_msg = {
     error: 'User not found'
 }
function findUserByUserID(user_id)
{
    const user = users.find(user => user.user_id === user_id);

    if (user)
    {
        return user;
    }  else
     {
        return error_msg
    }
}

const getUser = findUserByUserID('1112')
console.log(getUser)
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!