
What is the significance of, and reason for, wrapping the entire content of a JavaScript source file in a function block?
1 Expert Answer

Ian M. answered 03/26/19
JavaScript, Web Application Engineer
Scope control!
All global variables and functions become properties and methods of the window object. Try console.log(window) to see what global scope looks like. If you have custom functions and variables, they will appear as properties attached to the window object!
Wrapping everything in a function makes your "global" variables and functions less global: they become part of the outer function's scope. They will not be attached to the window object, but will rather only exist while the outer function is running. As soon as the function ends, all those variables and functions are purged from memory.
This is good because it provides better memory control, but more importantly it protects your code from being accidentally overwritten by other global variables or functions that just happen to have the exact same name. If you're working with several different modules, or if there are a team of developers, then it makes a lot of sense to keep code groups separate and unable to damage any other.
Ian
Still looking for help? Get the right answer, fast.
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.
Jesse B.
Could you provide a code snippet of what you are referring to?03/19/19