Home › Forums › JavaScript › Nesting functions: Good or Bad?
- This topic is empty.
-
AuthorPosts
-
December 31, 2013 at 3:39 am #159341RuggParticipant
Please excuse my ignorance, but is there anything wrong with nesting multiple functions inside a parent function, which is then called to execute the contents inside? I’ve successfully tested the output, but wasn’t sure if it’s frowned upon.
For example:
function myFunc() { var = myVariable; var = anotherVariable; function one() { // Do Something } function two() { // Do Something Else } function three() { // Do Something Else } } // Call Function myFunc();
January 3, 2014 at 4:39 pm #159594noahgelmanParticipantThis is a matter of scope.
With this set up it becomes much harder to call one(), two(), or three() outside the myFunc(). You can’t just use one() anywhere you want because you can only access it while inside myFunc().
Try to keep functions separate. If a function needs to use another function inside it, just call it.
function one() { // Do Something } function two() { // Do Something } function three() { // Do Something } function myFunc() { var = myVariable; var = anotherVariable; one() ; two(); three(); } // Call Function myFunc();
If you need to use the variables set in myFunc() in one(), two(), and three() then just pass them into the function
January 3, 2014 at 6:54 pm #159601__ParticipantOn the other hand, this is exactly how you get private methods/variables in javascript.
If your function is needed only inside the parent function, then declaring it inside the function means it won’t cause any problems with functions in other scope(s).
function count(){ alert( "1, 2, 3, 4, 5" ); } function backwardsDay(){ function count(){ alert( "5, 4, 3, 2, 1" ); } }
The inner
count
method doesn’t conflict with the one in the global namespace, plus, the global namespace can’t use it: onlybackwardsDay
can count backwards.January 4, 2014 at 5:37 pm #159656RuggParticipantIf your function is needed only inside the parent function, then declaring it inside the function means it won’t cause any problems with functions in other scope(s).
This is exactly the situation. All the functions within the wrapper are related and some share a common variable.
Thanks for the input!
-
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.