Why do we wrap Angular app inside a function? - javascript

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.

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.

Assessing variables outside scope of a function declaration

I have several functions that work together to accomplish one task. Each of those functions live in their own file. In my main file, I compose these functions to accomplish my task.
Because of this, many functions need access to the same variables. My initial approach was to declare these variables in my main file with the expectation that I could call them within my functions.
However, when I run them I get reference errors inside my functions. My current alternative includes passing these variables into each function but it doesn't seem too elegant. I also considered making a class but I run into the issue of not being able to separate the functions into different files (for organizational purposes).
// doSomething.ts
declare outerVariable
function doSomething() {
console.log(outerVariable)
}
// main
import doSomething from './doSomething.ts'
let outerVariable = 5
doSomething() // Reference Error: outerVariable is not defined
I don't think variable shadowing is an issue because I never create variables with those names in my functions.
Any idea on what's going on or a better way to structure the code?
Are there ways to accomplish what you are trying to do? Yes, but maybe that's not the way to go.
It seems you need to rethink your program structure as a whole.
First and foremost, polluting the global namespace is never a very good idea (in any programming language probably). If you are writing code using pure functional style, then yes, passing the variables as arguments to all the functions is how it's done. You can read a little about this on wikipedia (first paragraphs should give you a nice overview): https://en.wikipedia.org/wiki/Functional_programming
It also might be the case to minimize creating functions with side-effects as pointed in the comments of your question.
If the number of variables you are passing to theses functions is too large, perhaps you should consider splitting your code into smaller, more specialized functions/classes.
A single file usually contains only closely related functions or a single class.
Now, if you don't mind using objects, then you can pass to the functions one or more objects, grouping all your variables.
Also, the singleton pattern might be handy: https://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript.
Try es6 export const variable = somevalue
For example, you could pass your variables into functions as arguments
Maybe it's worth considering reorganising them into a class, so they could access common class fields
It's generally good to decouple your code entities from each other, so passing them as arguments is better than declaring globals usually

Javascript Eval and Function constructor usage

I'm currently experimenting on self replicating code. Out of love for the language I'd like to write it in javascript.
I'm working on a program that writes a function's code which in turn writes its function own code and so on. Basically, the desired process is this:
I manually create A function which returns code (which includes some randomness) and a numeric value (proposed solution to a problem).
I call this function a number of times, evaluate the results of each of those returned functions, and continue the process until I have code that is sufficiently good for what I'm trying to do.
Now, I have always been told how eval is evil, how never to use it and so on. However for my specific use case it seems like the Function constructor or eval are exactly what I'm looking for.
So, in short the question is:
Are eval/Function constructor indeed the best tools to use in my case? If so, I figured I'd use the Function constructor to scope the code executed, but is there a way to truly limit it from accessing the global scope? Also, what are some good practices for eval usage in my case?
I think I just figured out something I could use:
If I run my javascript code using node.js I can use the vm module which allows me to execute javascript code safely in a new context, and without letting the executed code have any access to the local or global scopes.
vm.runInNewContext compiles code, then runs it in sandbox and returns the result.
Running code does not have access to local scope. The object sandbox will be used as
the global object for code. sandbox and filename are optional, filename is only used in
stack traces.
You can see a full example here: vm.runInNewContext
This will allow me to eval code safely, and seems to be the safest way (I found) currently available. I think this is a much better solution than eval or calling the Function constructor.
Thank you everyone who helped.
Unfortunately I believe there is no way to prevent it from accessing the global scope. Suppose for example that in a web browser i evaled some code like this :
(function(window) {
eval(script);
)(null));
Any time the script tries to access window - it will get an error, since window is null. However someone who knew what they were doing could always do this :
var global = (function() {
return this;
}());
Since when you invoke a function in what Crockford calls the "function invocation style" then the this is always bound to the global variable.

What is the purpose of passing arguments to anonymous functions in this manner? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do JavaScript closures work?
I was playing around with the Google Closure Compiler, putting in random code to see what it would do.
It rewrote one of my functions to look something like this:
(function(msg) { console.log(msg); })("Hello World!");​​​​​​​
Where it appears that "Hello World" is the argument passed as msg to the anonymous function preceding it. I was looking at it for a moment, and had thought that I had seen something similar in jQuery plugins that look something like:
(function( $ ) {
...
})(jQuery);
Which now makes more sense to me, in the scope of conflicts with $. But what is the primary reason or purpose for passing arguments into an anonymous function like this? Why wouldn't you simply define the arguments as variables within the function? Is there any performance or flexibility advantage to writing functions like this?
There is one significant difference connected also to scope. The following code:
(function(msg) { console.log(msg); })("Hello World!");​​​​​​​
is in some circumstances cleaner in terms of namespace pollution than this:
var msg = "Hello World!";
console.log(msg);
because the second code leaves variable after it is no longer needed, but may interfere with other parts of the code.
This is especially important when you execute the mentioned code outside any other function: in such case msg variable would be available everywhere on the page, as global variable.
Basically, it's always a good idea to keep your code wrapped in this: (function(){/*code*/}()); to prevent your vars from colliding with other peoples vars.
I think the main thing closure compiler is getting at is saving the 5 characters:var and =.
It depends a bit on the context. There are some conditions where the compiler won't try to inline any function at all (if the scoping function contains "eval" for instance). If this is a in global scope and you are running in ADVANCED mode, it is simply that the inlining opportunity appeared after the compiler stop trying to inline functions (or there is a bug in the inlining code and it missed the opportunity). If you run your sample output through the compiler in ADVANCED mode, you get this:
console.log("Hello World!");

What is the primary purpose of function expression in Module Pattern

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...

Categories