This simple trick will make your JavaScript code way less buggy

Hello 👨‍💻 && 👩‍💻!

Today, I’ve got a simple trick for your JavaScript development, that will result in your code being way less buggy.

I noticed this issue when doing code reviews (which I btw love to do!).

Buggy code

So, what’s the case?

Let’s imagine a very popular case of having an array of objects with user information and a variable that stores an ID of currently selected user, it may look like this:

const users = [
    {id: 12, name: "Peter"},
    {id: 13, name: "Katy"},
    {id: 14, name: "Jonathan"},
    {id: 15, name: "Drew"},
];

let selectedUserId = 91;

const getCurrentUserName = () => {
    const user = users.find(user => user.id === selectedUserId);
    return user.name;
};

document.body.innerText = getCurrentUserName();

Do you see an issue here? 🤔

Well, what would happen if from some reason, the variable selectedUserId stores a value as a string or it will store an ID of a user object, that is not included within the users array?

Well, in that case, you might expect the following error in your application (alongside with the application being broken and not functioning in the browser for the user):

Uncaught TypeError: Cannot read property 'name' of undefined at getCurrentUserName (:3:17) at :1:1

Fixed code

What you should do instead is just a small fix, that will prevent dozens of bugs in your code and the fix is the as follows:

const users = [
    {id: 12, name: "Peter"},
    {id: 13, name: "Katy"},
    {id: 14, name: "Jonathan"},
    {id: 15, name: "Drew"},
];

let selectedUserId = 91;

const getCurrentUserName = () => {
    const user = users.find(user => user.id === selectedUserId);

    if(typeof user === "undefined") {
        console.warn('It seems there is incorrect value stored as ID of current user.');
        return null;
    }

    return user.name;
};

const currentUserName = getCurrentUserName();

if(currentUserName !== null) {
    document.body.innerText = currentUserName;
} else {
    document.body.innerText = "";
}

As you can see in the code above, there is just small tweak and that is adding a precautionary check after calling .find() function, because that function will return undefined, if nothing is found – and provided that your code is not written to handle such use case, you can expect your application failing.

Final thoughts

So what do you say? 🙂 Will this small trick make your code way less buggy?

Are you the one being guilty of the aforementioned negligence?

Or did it caused any issues with your application in the past?

Don’t be shy to share your story 🤗!

Also, would you like to hear similar code-reviews stories? If so, let me know in the comments below!

Anyways, thanks for reading and I’ll see you in the next article! 🤓

Yours in coding,

Ivan


Also, thanks: David Clode on Unsplash for the featured image in this post.