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

I'm having a tough time understanding what's going on here

Although I know these functions making my code shorter, I'm having a hard time tracing what is truly happening.

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

1 Answer

Luca Tardito
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Luca Tardito
Front End Web Development Techdegree Graduate 17,602 Points

Hi Nathan, so something for me looks a bit confusing, for example I don't understand why in the main function (createLi) there is an argument that it seems don't be used in those functions. anyway let's try to understand better what is going on here: on line 2 and on line 7 there are two nested functions, the first one is getting tree arguments and is doing the following:

  • create a new element and save it inside a constant called element (line 3), then set the property (second argument that we pass into) of that element equal to the value (third argument that we pass into). the second function, on line 7 is doing the following:
  • call our createElement function and save it into an constant called element ( notice that the name it's the same but it's not the same variable that you find on line 3. then append that element as child in a list item. I hope to help you, this code is a bit tricky because some variables and functions are the same names but are different because they are define in two different functions.