Fuego DeBassi
Fuego DeBassi

Reputation: 3027

How can I write this repetitive JS function more cleanly?

I have a function that will populate a table #contents with some rows. It looks like this:

// data is defined in data.js
function populateTable() {
    for(var i = 0; i < data.length; i++) {
        if (data[i].type == "MOV") {
            var row = '<tr><td><a>' + data[i].title + '</a></td>';
            row+= '<td><a>' + data[i].year+ '</a></td></tr>';
            $("#contents").append(row);
        } else {
            var row = '<tr><td><a>' + data[i].title + '</a></td>';
            row+= '<td>' + data[i].year+ '</td></tr>';
            $("#contents").append(row);
        }
    }
}

I'm going to potentially have a bunch of content types, so this IF statement will get a good deal bigger, I'm wondering what a better way to handle the repeated elements inside the IF statement might be?

Upvotes: 0

Views: 78

Answers (2)

Abhishek Anand
Abhishek Anand

Reputation: 477

You do not need to repeat the string that do not vary for each if statement, That would shorten up your code a lot

function populateTable() {
    function getUniqueString({type, year}) {
        if(type == 'MOV')
            return `<a>${year}</a>`
        return `${year}`
    }
    for (const d of data) {
        $("#contents").append(`<tr>
            <td><a>${d.title}</a></td>
            <td>${getUniqueString(d)}</td>
          </tr>`)
    }
}

Upvotes: 3

Winston Brown
Winston Brown

Reputation: 97

Your using var so I am assuming your a beginner. So watch a youtube video or research : template strings and higher order functions.

Template strings or much cleaner way of writing strings because you don't have to use the + sign

Higher order functions are better and cleaner way of looping over arrays.

Oh it also does not hurt to use some line spacing. It really improves readability

Upvotes: -2

Related Questions