Lets say you are making a function that stores properties of pen, like function pen, and properties color, shape, lvl of ink, those properties only exist inside of your function. That is good because you avoid conflict with other parts of your code, but if you need to call those properties or change them? You could do it easily by nesting a function inside your function pen that do whatever you want with those properties, those properties are inside that child function scope but out of the rest of the code scope. You can even call that nested function as argument in another function, it create many possibilities and once you get the hang of it you spend less time coding and have a cleaner code, less prone to bugs, also since those properties (or variables, methods,..) are inside of the function scope you avoid memory leaks.
You use a function to create such an object if you want an object (ES6 Classes are just syntactic sugar over functions), but the other way around doesn't work if you ever want more than one single pencil in your program.
3
u/el_graveto May 28 '19 edited May 28 '19
Lets say you are making a function that stores properties of pen, like function pen, and properties color, shape, lvl of ink, those properties only exist inside of your function. That is good because you avoid conflict with other parts of your code, but if you need to call those properties or change them? You could do it easily by nesting a function inside your function pen that do whatever you want with those properties, those properties are inside that child function scope but out of the rest of the code scope. You can even call that nested function as argument in another function, it create many possibilities and once you get the hang of it you spend less time coding and have a cleaner code, less prone to bugs, also since those properties (or variables, methods,..) are inside of the function scope you avoid memory leaks.