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 DOM Scripting By Example Improving the Application Code Refactor 1: Create List Items

Refactor 1: Create List Items Would this not be considered good practise?

function createLI(text) {
    function createElement(elementName, property, value) {
        const element = document.createElement(elementName);
        element[property] = value;
        li.appendChild(element);
        return element;
        }
    const li = document.createElement('li');
    const span = createElement('span', 'textContent', text);
    const label = createElement('label', 'textContent', 'Confirmed');
    const checkbox = createElement('input', 'type', 'checkbox');
    const editButton = createElement('button', 'textContent', 'edit');
    const removeButton = createElement('button', 'textContent', 'remove');
    return li;
}

2 Answers

Steven Parker
Steven Parker
231,236 Points

This function creates several constants, never uses most of them, and then returns causing them all to be disposed. Best practice would be to skip all the variable creation. And the inner function doesn't need to return the element.

It might also be considered a "best practice" to provide "li" as an argument to the internal function instead of relying on accessing it from the outer scope.

Thanks Steven,

In the next set of videos we cleaned up the code quite a bit.

Looks like I've got a long way to go.

This worked pretty well for me. No need for a second function, and no const creation.

function createLI(text) { const li = document.createElement('li');

function createElement(elementName, property, value){ const element = document.createElement(elementName); element[property] = value; li.appendChild(element); return element }

createElement('span', 'textContent', text) createElement('label', 'textContent', 'confirmed').appendChild(createElement('input', 'type', 'checkbox'));; createElement('button', 'textContent', 'Edit'); createElement('button', 'textContent', 'Remove'); return li;

}