Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

James Barrett
James Barrett
13,253 Points

How to make this JavaScript form validation more efficient

Hi there, to save me time formatting the code, I will provide the code snippet on GitHub:

https://github.com/jamesbarrett95/www.jacksonjacobdeveloper.com/blob/master/js/contact.js

I am just wondering how I could make this more efficient? It definitely works, however there is a lot of repeated code.

Any help will be greatly appreciated.

Thanks, James.

1 Answer

Steven Parker
Steven Parker
229,788 Points

Code can often be compacted by combining operations and eliminating temporary variables. And some conditional statements can be converted to expressions. Conditional statements around assignments can often be replaced with the ternary operator.

For starters, you could condense this section of code:

        if(error == 0) {
            return true;
        } else {
            return false;
        }

Into this single statement:

        return (error == 0);

And something like this:

        var errorname = document.getElementById("errorname");
        var user_name = document.contactform.user_name.value;
        if (user_name === "") {
            errorname.style.visibility = "visible";
            error = 1;
        } else {
            errorname.style.visibility = "hidden";
        }

Could be condensed to this:

        var user_name = document.contactform.user_name.value;
        document.getElementById("errorname").style.visibility = user_name ? "hidden" : "visible";
        if (!user_name) error = 1;

I agree with your answer but I would recommend you break down the code so that users of all levels can understand how and why these shorthand alternatives work.