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

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
221,888 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,372 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".