I recently watched a JavaScript video tutorial containing code similar to this one:
(function (){
var b = 10,
c = 20,
d = 50;
var e = function(){
return b + c + d;
};
return e();
}());
This is a common JS coding pattern.
The author said that this is an example of a procedural approach in Javascript code. I don’t understand that, can you please explain.
Let’s start by saying the above is a self-invoking anonymous function:
The above is a fairly poor example in my opinion, but consider the following change:
We’ve taken the above code and added a
var f =in front of the function. This returns the value ofe()from the inner function tofand now you have a valuefto be used elsewhere. Since the variablesb,c,d,eare declared within the function scope of the anonymous function, we can ensure that they will not be tampered with. This is a way to do private variables in JavaScript. Now say you had10 + 20 + 50may places within your code. You could run this anonymous function at the beginning and substitute those occurrences withf. This idea of abstracting out code into various procedures is why it’s referred to as Procedural Programming.This is mainly used to make code easier to read, easier to follow/debug and lets you abstract commonly used chunks of code into well written snippets of code.
Read more
Self-Invoking Functions
Purpose of Self-Invoking Functions
Procedural Programming
More Procedural Programming
and this moves you into Closures