What is the primary purpose of function expression in Module Pattern - javascript

I know that Module Pattern is very useful and powerful in Javascript programming.
I recognized that pattern in Eric Miraglia's blog for the first time , but I am wondering one thing.
In other blogs and articles that explain Module Pattern, I notice that their sample codes are slightly different from Eric's article, that is, they use function expression with parenthesis rather than function statement, for example, the article from ben cherry is one of them.
Is there any specific reason to use function expression rather than function statement?
Please explain with easy way, I just entered into Javascript Programming world :)

The Miraglia pattern is the same, defining an anonymous function and executing it. The difference is that in order to use the features of the module, you must have a reference to an instance somewhere. Assigning the module to a global variable (YAHOO.*) is a way to retain the reference at a globally known spot, especially important for frameworks (like YUI).
Sometimes you don't need that reference. For example, if you are writing JavaScript for a web page, you often bind events to functions using selectors (ids / types, etc.) That really removes the need for any global reference to your module function.
Hope that make sense...

Related

Is it possible to write every function as "pure function" in Google Apps Script?

I am interested in functional programming, so I decided to try this approach on the scripting environment of my Google Sheets file, and you know that the scripting language is Google Apps Script, which is basically javascript. And it even supports some (if not all) ES6 syntax.
The problem is that I cannot directly run any code, for example:
let a = 4;
Logger.log(a);
I mean, I cannot run it globally, I need to define a function with any name, and then place the code inside that function, and I can run the function, so the function runs the code inside.
So, maybe you ask, "why this behavior makes a problem writing pure functional code?" well, because, as I know, two of the most important factors about pure functions are:
1) We must not use global variables/functions inside a function, instead we must pass as parameters (and then as arguments of course).
2) defining function inside a function is often not very good idea in terms of readability and organization of the code.
So, I want to define more functions (to do some stuff), not just one "main" function, and I could not find any way, any single way to write code (as a whole) without violating at least one of the two statements above.
So, I mean, I can not write anything without making at least one non-pure function.
As a user explained in the comments:
Your 1st assumption is partially incorrect. A function must not depend on global, mutable variables, but it may depend on global constants and global pure functions. However, often you rather want to pass a function dependency as an argument to obtain a more general higher order function. Your 2nd assumption is merely opinion based.
So you could, for example, define a main function to run your code as a whole while defining functions inside the main function to achieve functional programming with Apps Script.

Why do we wrap Angular app inside a function?

I'm learning Angular and in all the resources I've used so far I saw this in the app.js file:
(function () {
\\\myAngularModules
})();
The most commonl explainantion is an unhelpful "it's just good practice".
Questions:
Is wrapping our Angular JS code in a function really good practice? Why?
What sort of function is it and what does it do?
Please give examples where possible.
This is what is known as an immediately invoked anonymous function (IIFE). It allows us to create a new function scope and immediately run the code so that no variable or other items we create "leak" out and manipulate the global scope.
Leaking of your code into the global can impact other modules or 3rd party code. This also helps protect your code by making you think about what objects you are using that are not declared in your local scope.
http://gregfranko.com/blog/i-love-my-iife/ as a more detailed explanation that covers the general idea other esoteric things like minification benefits.
Is wrapping our Angular JS code in a function really good practice?
Why?
This is good practice and is called module pattern. As a pattern has it advantages and it disadvantages. However, it is one of the most used patterns in the JS world. In a few words, it allows you to declare as you want your variables, your functions etc. without having any conflict with any js code you use in your app.
For further information on the above, please have a look here.
What sort of function is it and what does it do?
It is a classic function. Nothing more nothing less. Using the invoking operator () at the end, we call the function, to be executed. The latter is also known as IIFE, immediately invoked anonymous function.

Formal defintion of function closures in computer science

at the moment I am writing a scientific expose. A part of the content is about the definition of closures in our developed DSL. However, I was not able to find references of how to formally describe function closures in computer programming. I must admit I have searched in only a handful of programming books. Without any success.
What I really need is the formal, precise and maybe mathematical definition of the concept of function closure in computer programming. Using a formal definition we may find a way to define our special kind of closures in a convenient and precise way.
Is there any standard notation/description out there?
If not maybe one of you theorist can give me a hint, how to elegantly describe them ;)
So, since I already created a definition on my own, I want to share it with everyone, that is looking at this question.
The following definition is a short version and product of my own thoughts, so do not simply adopt it without thinking through it.
Closures are an implementation technique to implement lexically scoped name binding.
The operational view of a closure is the tuple of an environment E that binds free variables of the function f, and f itself: (E,f). Let E[in1] = x bind the value of in1 to an arbitrary x. The application foo(in2) of the closure (E, foo(in1, in2)) gets then evaluated to the same result, as foo(x, in2).
Other than partial evaluation, the functions source code is not duplicated. The environment is evaluated at run-time.
What do you think?

Various openings to creating the revealing module pattern

When we initiate a plan to build a revealing module pattern, what is the biggest difference between constructing the pattern to start this way...
var MODULE = function() {}();
and constructing the pattern to go this way...
var MODULE = (function() {})();
Benefits? Purpose?
Also as an additional question, will either of these techniques allow jQuery to process without passing the $ into them?
Thanks for any feedback!
There's a jsHint option to warn when functions aren't wrapped in parens. The description of the option reads as follows:
"This option prohibits the use of immediate function invocations without wrapping them in parentheses. Wrapping parentheses assists readers of your code in understanding that the expression is the result of a function, and not the function itself."
As for your question about jQuery; Yes, jQuery will be available, provided you've included it, obviously. Having said that, I would still recommend passing '$' or 'jQuery' as a parameter to your function. If you don't, every time you reference it, the engine will have to go up to the parent scope to find it. Not a huge deal, but less efficient, especially if you make heavy use of jQuery. If you pass it in, then jQuery is defined in your function's scope, and won't need to go searching in ancestral scopes for it.

Javascript Function Scope

This is perhaps a dumb question, but I am new to Javascript and desperate for help.
If the Javascript engine will look for global variables outside of a function, then what is the point of passing parameters to it? What do you gain?
I understand that global variables are generally frowned upon, but I still don't understand the purpose of passing variables. Does it have something to do with data encapsulation?
There's a few magic words that are used by programmers to describe different kinds of functions. Here's a few:
Re-entrant
ThreadSafe
Referentially Transparent
Idempotent
Pure
Side-Effects
You can look some of them up if you want a headache. The point is that Computer science and engineering progress has always been about reducing complexity. We have spent quite a lot of time thinking about the best way to write a function to achieve that goal. Hopefully, you can stuff tiny bits of your program into your head at a time, and understand those bits, without having to also understand the overall functioning of the entire program simultaneously, or the detailed implementation of the insides of all the other functions. A function that uses global variables can't do that very well because:
You can't guarantee that the global variables exist
You can't guarantee that the global variables are what you think they are
You can't guarantee that other parts of the program haven't modified those variables in a way you didn't expect.
You can't easily generalise to use the function multiple times on multiple sets of variables.
You can't easily verify that the function works as advertised without first setting up the function's external environment and its dependencies.
If the global variables have changed in a way you didn't expect, it's really hard to track down which part of the program is the culprit. It could be any of 500 different functions that write to that variable!
On the other hand, if you explicitly pass in all the data a function needs to operate, and explicitly return all the results:
If something goes wrong with any of those variables, it's easy to find the source of the problem
It's easier to add code to verify the "domain" of your inputs. Is it really a string? Is it over a certain length, is it under a certain length? Is it a positive number? is it whole, or fractional? All these assumptions that your code needs to operate correctly can be explicit at the start of the function, instead of just crossing your fingers and hoping nothing goes wrong.
It's easier to guess what a particular function will actually do, if its output depends only on its input.
a function's parameters are not dependant on the naming of any external variables.
And other advantages.
if you were only going to use global variables that the functions worked on then you'd always have to know the inner workings of the functions and what your global variable names had to be for them to work.
also, something like Math.abs(n) would be hard to call twice in one line if using global variables.
Functions are reusable components of your code, that executes a particular snippet on the provided variable exhibiting varying behavior.
Encapsulation comes from being Object Oriented. Functions are more for giving structure to your program.
Also, you shouldn't undermine the execution time of a method, if the variable it access exists in the context rather than being global.
If you don't need parameters to be passed to functions, then, you really don't need functions.
Functions are usually (and should be) used to provide code re-use -- use the same function on different variables. If a function accesses global variables, then every time I use it it will perform the same action. If I pass parameters, I can make it perform a different action (based on those different parameters) every time I use it.
One of the main benefits is that it keeps all the information the function needs, nearby. It becomes possible to look at just the function itself and understand what its input is, what it does, and what its output will be. If you are using global variables instead of passing arguments to the function, you’ll have to look all over your code to locate the data on which the function operates.
That’s just one benefit, of many, but an easy one to understand.
Global variables (in any language) can sometimes become stale. If there is a chance of this it is good to declare, initialise and use them locally. You have to be able to trust what you are using.
Similarly, if something/someone can update your global variables then you have to be able to trust the outcome of what will happen whenyou use them.
Global variables are not always needed by everything so why keep them hanging around?
That said, variables global to a namesapce can be useful especially if you are using something like jquery selectors and you want to cache for performance sake.
Is this really a javascript question? I haven't encountered a language that doesn't have some form of global variables yet.

Categories