More recent posts can be found on medium.com/@devbyrayray
What is a scope
A local scope is created by a function. Everything that is defined in there will only be accessible inside that, or child scopes (functions inside that function). Inside a local scope, you can access the Global scope or a parent scope (parent function)!
In the example, above you see that there will be an error when you try to get the variable in the Global scope that is defined in a child scope.
If you want to prevent yourself from accidentally changing the value of a variable in a different scope, just start your function with declaring your variables.
This is also called as Hoisting. This will prevent overriding accidentally your variables.
Well, some more experienced developers won't agree for some reason. But in my experience, it prevents a lot of issues!
Private & public
Developers that already worked with other libraries or frameworks and checked the source code know's that the function's you can use in your own code, have smaller function's inside it, that you can't use or access.
This is because there are private and public functions (properties). A public function is accessible from the other scope. A private function is only accessible from the same scope, so it is hidden from another or parent scope.
Since we created a module we can now see the difference between private and public. If we try to access the private function it will give an error.
This function is only accessible in the module itself. Not from outside! So a private function is very useful for internal things like difficult calculations, error handling etc.
From our module, the public function's (also called methods) are accessible from outside the module.
Public functions are there to execute them from outside your module. If you take for example the Google Maps API. It is full of public and private methods.
Map() method is a public function! This public function execute a lot of private functions. So you only have to call 1 function and it will handle's the rest for you!
How to create private and public functions
If you check the example module it is very simple! A function will become public if it is returned. Otherwise, it stays private! In the module there is the
So if we want to make the other function also public we can just add it to the object. We can do that by adding this function inside the object, but also like this
Most of the time this is the way I would setup my modules:
I set it up like this because it is very readable of which function is public or private. In just 1 view you can see that every function attached to the object (that is returned) will be public, the rest will be private!