DEV Community

Matt Ericsson
Matt Ericsson

Posted on

Looking for JavaScript/jQuery Resources to Write Cleaner, Concise Code (Code Examples Provided)

As an individual in a more frontend design-driven role with the need to sometimes create custom JavaScript, I find myself always wanting to write cleaner and more concise code.

To preface, I'm not looking for you to debug the code below, but to provide your insight. What are some good resources to reference when you were looking for the best approach to writing simpler code?


I was working on a project recently that involved writing some custom functions for a step-by-step form (first two steps included in this post). This will evolve into steps 3 and 4, but they are on the back burner for now.

  1. Select a membership level based on the amount you're willing to give over the course of the year. This will provide membership details based on the level you chose before continuing to step 2.
    • The membership values will change by 50% if you're a recent grad.
    • You can't be a current student and a recent grad, so the current student option will be disabled if recent grad is checked.
  2. Give a few minor details like first and last name as well as your email. The form will submit what the user also chose in step 1 and then redirect the user to another site where they can then follow steps 3 and 4.
  3. Create your membership account.
  4. Register your account by providing additional details.

How I set this up had four main functions with room for smaller tasks:

  • changeAmount();
    • Main top-level function that would change the membership values based on whether or not 50% off was checked along with various underlying conditional functions.
  • changeDiv();
    • If a membership level is checked, then its respective membership listed benefits will show and all others will be hidden.
  • showLevel();
    • If a membership level is selected, then the values based on whether or not they are 50% off will populate within step 2.
  • revealSteps();
    • Show steps individually (1-4). This basically hides all other views based on the step you're currently on.

Given the nature of jQuery, it just seemed like a lot and the code was repetitive. I feel like the cleaner approach would be to try and cut down on repetition by keeping it as generic as possible. I've included a short walkthrough below so you can gain a better understanding. Apologies in advance for it not being highlighted in correct syntax!


If Recent UNC Grad (50% Any Level) IS checked, then all membership annual and monthly values will change by 50%.

if($('input[name=halfoff]').is(':checked')) {
    $("#recentUNCGradLevel2 label").removeClass('bg-white').addClass('bg-secondary  text-white');

    var radioTarHeelAnnualValue = (100 / 2);
    var radioTarHeelMonthlyValue = (8.34 / 2);
    $("#tarHeelLevel3").html("<span class='membership-name'>Tar Heel</span>" + "\n" + "<span class='d-block'>$" + radioTarHeelAnnualValue + " Annually</span>" + "\n" + "<span class='d-block'>$" + radioTarHeelMonthlyValue + "/month</span>");
    $(".display-annual-amount.tarHeelAnnualAmount").html('$' + radioTarHeelAnnualValue);

    $("#currentUNCStudentLevel2").html("<label id='currentUNCStudentLevel4' class='btn btn-primary  rounded  disabled'><input id='currentUNCStudentLevel' type='radio' name='what' value='Current UNC Student' data-divid='B' disabled>Current UNC Student" + "\n" + "<span class='d-block'>$25/Annually</span>" + "\n" + "<span class='d-block'>&nbsp;</span></label>");

    var radioRamAnnualValue = (200 / 2);
    var numRamMonthlyValue = Number(16.67 / 2);
    var roundedRamMonthlyString = numRamMonthlyValue.toFixed(2);
    var roundedRamMonthlyValue = Number(roundedRamMonthlyString);
    $("#ramLevel3").html("<span class='membership-name'>Ram</span>" + "\n" + "<span class='d-block'>$" + radioRamAnnualValue + " Annually</span>" + "\n" + "<span class='d-block'>$" + roundedRamMonthlyValue + "/month</span>");
    $(".display-annual-amount.ramAnnualAmount").html('$' + radioRamAnnualValue);

    ...

If a membership level is selected, then the values based on whether or not they are 50% off will populate within Step 2.

showLevel: function() {
    $(document).ready(function(){
        $("input[type=radio]").change(function(){
            if($("input[type=radio][name=what][value='Tar Heel']").is(':checked')) {
                $(".display-level.tarHeel").addClass('d-inline-block');
            } else {
                $(".display-level.tarHeel").removeClass('d-inline-block').addClass('d-none');
            }

            if($("input[type=radio][name=what][value='Current UNC Student']").is(':checked')) {
                $(".display-level.currentUNCStudent").removeClass('d-none').addClass('d-inline-block');
            } else {
                $(".display-level.currentUNCStudent").removeClass('d-inline-block').addClass('d-none');
            }

            ...

Based on which membership level is selected when Recent UNC Grad (50% Any Level) IS CLICKED, this will make sure that the membership level and annual amount are displayed within Step 2.

$(document).ready(function(){
    $("input[type=radio]").change(function(){
        if($("input[type=radio][name=what][value='Tar Heel']").is(':checked')) {
            $(".display-level.tarHeel").addClass('d-inline-block');
        } else {
            $(".display-level.tarHeel").removeClass('d-inline-block').addClass('d-none');
        }

        if($("input[type=radio][name=what][value='Current UNC Student']").is(':checked')) {
            $(".display-level.currentUNCStudent").removeClass('d-none').addClass('d-inline-block');
        } else {
            $(".display-level.currentUNCStudent").removeClass('d-inline-block').addClass('d-none');
        }

        ...

As you can see from all of the code above, this is a lot if you have 10 options to choose from; this would be daunting if you had way more. Maybe for this case my approach was ok, but I'd just like to go about refining my code moving forward.

Thanks and greatly appreciated!

Top comments (2)

Collapse
 
sualko profile image
Klaus Herberth

For me the book "clean code" was an eye opener. It's a bit extreme, but the fundamentals are awesome. The most important point is to have small functions with good names. This helps you to structure your code and improves readability.

For example I would move the add/remove class line to it's own function. Personally I also don't like the chaning, because it's terrible to read. Also move all const to the outside of your function. Document ready inside a function is also pretty unusual.

Your code, espacially the template part, could be improved by using string literals.

Happy coding and I hope we will see an refactored version.

Collapse
 
mjericsson profile image
Matt Ericsson

This is exactly what I was hoping to hear.

The add/remove class recommendation makes total sense, I just hadn't thought of it that way. The chaning is something I want to try and avoid and make the code more generic. Good point on the document ready, I'll have to make an adjustment.

Excellent point on string literals, I could definitely utilize that to improve the readability.

Appreciate the insight!