3
\$\begingroup\$

Can someone please review the code and suggest any improvements / changes? Note that this method works but wanted to see if there is a better way for self learning purpose JavaScript/jQuery.

Example https://jsfiddle.net/tjmcdevitt/Lx0vnb89/4/

var AppType = [
    ['All'],
    ['API'],
    ['AWS'],
    ['Web']
];

    $.each(AppType, function (index, AppType) {
        var option = $('<option></option>').attr("value", AppType).text(AppType);
        $("#ddlApplicationType").append(option);
    });
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

I have a few suggestions for optimizing your code.

Since ES6 came out it is considered best practice to declare variables as const. It is also a good practice to declare your variables at the top of your script. For example you are selecting the element #ddlApplicationType everytime you loop over your array. That is not necessary. Just select it once at the top of your script and reuse it as often as you want in your code by referencing the variable const selectApplicationType. If you know that you are going to reassign a variable you can use the let keyword. Like I did in the $.each function. temp gets reassigned everytime the $.each loops over it. I declared it inside this function because it is a temporarly used variable and will never be needed in the global scope. When using DOM elements you should check if they exist first. For example if you have multiple pages and a DOM element referenced in your code is missing all the following code will break. In the example below I used string literals. I think it makes the code a bit more readable. I hope I could help you.

const AppType = [
    ['All'],
    ['API'],
    ['AWS'],
    ['Web']
];
const selectApplicationType = $("#ddlApplicationType")

if (selectApplicationType.length > 0) {
    $.each(AppType, (index, AppType) => {
        let temp = `<option value="${AppType}">${AppType}</option>`
        selectApplicationType.append(temp)
    })
} else {
    console.log(`Element #ddlApplicationType is missing`)
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.