HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Anyway to shorten these for statements?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
anywaythesestatementsshortenfor

Problem

Just seeing if there is anyway to shorten these for statements?

...      
      fillMonthSelect: function() {
        var month = new Date().getMonth() + 1;

        for (var i = 1; i '+i+''));
        }
      },

      fillYearSelect: function() {
        var year = new Date().getFullYear();

        for (var i = 0; i "+(i + year)+""));
        }
      },
...

Solution

String building in code is typically messy, especially without a native String.Format() or sprintf() in Javascript. Building HTML is the worst offender, too.

Other than using a templating engine, like ICanHaz.js (which this use case alone doesn't really justify), you could also build a helper function for creating option tags.

function buildOption(value, isSelected) {
    return ""+value+"";
}


If you're building a lot of these drop-down options, it might makes things more readable:

for (var i = 0; i < 12; i++) {
    var option = buildOption(i + year, i === 0);
    $('.card-expiry-year').append(option);
}


It's a good idea to avoid long lines/sections of code which have a simple purpose, but have to be read carefully to understand what they do (complicated regular expressions are a good example).

Extracting that functionality into a function avoids this, because the function signature is all someone would need to read to understand what it does.

Code Snippets

function buildOption(value, isSelected) {
    return "<option value='"+value+"' "+(isSelected ? "selected" : "")+">"+value+"</option>";
}
for (var i = 0; i < 12; i++) {
    var option = buildOption(i + year, i === 0);
    $('.card-expiry-year').append(option);
}

Context

StackExchange Code Review Q#15249, answer score: 3

Revisions (0)

No revisions yet.