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

Why using a function inside another function??

Hi guys,

please can you explain me this step?

'''function createLI(text) { function createElement(elementName, property, value) { const element = document.createElement(elementName) ; element[property] = value; return element; }'''

in particular I do not understand what is the gool of putting a function inside another function. In this particular case wouldn't it be better to put the function createElement outside this function? I cannot understand the meaning of using that. Thanks

2 Answers

Steven Parker
Steven Parker
231,236 Points

This is a private function.

By defining createElement inside the createLI function, it is limited in scope and can only be used by code (including other functions) inside createLI. This prevents any name conflict with the outer scope, and also prevents any future changes to other functions in the outer scope from affecting the behavior of this function.

If this were a function of general usefulness, and you expected to need it in other parts of the program, it might make more sense to define it in the outer scope instead so it could be shared.

Christopher Debove
PLUS
Christopher Debove
Courses Plus Student 18,373 Points

Well due to encapsulation of the code in the DOMContentLoaded handler, all the code is "private".

I think it would be more optimized to create the function "createElement" on this scope to avoid recreating it at each call of createLI. The way scope is working, and function now is scoped. The reference is recreated each time with the closure of the parent function "createLI".