Two forces that can cheat lexical scope:
- Eval - By allowing the user to create/modify variables by passing in a string to eval
- With - By creating a new variable in the whole new lexical scope (inside the containing function scope)
most of the optimizations the javascript engine does will be pointless if there is eval()
or with
.
So it simply doesn't perform the optimizations at all #long live lexical scope
Traditional way of thinking -> Write function and then add code to it. Converse -> Wrap any arbitrary section of code and then add a function declaration around it Benefits of this converse
- Principle of least knowledge
- Collision avoidance
- Global namespace -> Libraries avoid collision by using a single object with unique name and gives access to properties
- Module Management -> Dependency managers handle namespace issue by using the scope rules
Executes immediately unlike normal function call. The variables and functions inside this function expression will have the scope only inside this function and will not pollute the global namespace.