Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
208,478 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;

}