I'm learning JavaScript at the moment and I don't quite understand when to write a function into a variable.
For instance, both of the following code blocks do the exact same thing in Node.js:
var onReq = function(req, res) {
res.write('Hello');
};
http.createServer(onReq).listen(3000);
and
function onReq(req, res) {
res.write('Hello');
}
http.createServer(onReq).listen(3000);
Which is the best method to do according to best practices, and why?
Usually I'll only use a var funcName = function(){} when I would need to redefine the action(s) for that function later on. For example:
var foo = function(a){ return a * 2; }
var bar = foo(2);
foo = function(a){ return a / 2; }
bar = foo(bar);
Otherwise, for most purposes (assuming it's not a callback or a modifier) declaring a function "classically" is usually acceptable.
I default to the non-variable function onReq(){} version. It's not a concious decision I've made, but thinking about it brings forth these arguments:
It looks cleaner.
It is conceptually simpler: it's just a function, while the other is a function and a variable. It's a small thing, but I find it valuable none the less.
It assures me that onReq will always refer to that function body - one less thing to consider when reading the code. Sort of like marking a variable as final in Java.
Keeps me from "accidentally" replacing the function, causing unintended side effects elsewhere.
I see that nobody mentioned (directly and practically - which seems this question is about) the reason for which I personally find most useful for storing functions in variables. That reason is dealing with a complex logic that requires a lot of choices (e.g. if's) to determine further course of action for which different functions should be called, possibly with different sets of inputs as well. It makes code cleaner when that further course of action is launched in just one place, at the end of our logic.
function fooA (input) {...};
function fooB (input) {...};
let chosenHandler;
let chosenInput;
// Here we establish which function is relevant
if (someCondition) chosenHandler = fooA;
else chosenHandler = fooB;
// Here we establish which parameter should be used
if (someOtherCondition) chosenInput = 'First input';
else chosenInput = 'Second input';
// Call chosen function with chosen parameters - one place, nice and clean
chosenHandler(chosenInput);
If we tried to call functions directly, the code would get much more messy and get the messier the more complex the logic is.
Here is an explaination:
There is a distinction between the function name and the variable the function is assigned to:
The function name cannot be changed, while the variable the function is assigned to can be reassigned.
The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement).
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope
According to John Resig's JavaScript as a First Language article, your first code block is considered as best practice.
I personally have encountered certain issues with calling local functions (functions declared inside other functions) when using non-variable syntax in some versions of IE (most likely IE8 or lower) while variable syntax did work as expected.
Given that functions should not be declated in global namespace, most of functions are local, and therefore it makes sense to use variable syntax for functions always.
I see some different opinions here, but most of them are more based on what you think is better or not, but i don't see the technical reasons on when to use one or another, but for sure there are technical restrictions or advantages in use one declaration formula or another. I'm really a beginner with javascript and I don't feel confident to advise on it, but I will propose a case in which storing a function in a variable is not functional.
In the code below, defining an Angular filter, if I define the function inside a variable, then I can't successfully call it from the filter method. Could anyone explain me the technical reason on this?
See the code (commented is not working):
angular
.module('loc8rApp')
.filter('formatDistance', formatDistance);
function formatDistance(){
return function (distance) {
var numDistance, unit;
if (distance && _isNumeric(distance)) {
if (distance > 1) {
numDistance = parseFloat(distance).toFixed(1);
unit = 'km';
} else {
numDistance = parseInt(distance * 1000,10);
unit = 'm';
}
return numDistance + unit;
} else {
return "?";
}
};
};
var _isNumeric = function (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
/*
var formatDistance = function () {
return function (distance) {
var numDistance, unit;
if (distance && _isNumeric(distance)) {
if (distance > 1) {
numDistance = parseFloat(distance).toFixed(1);
unit = 'km';
} else {
numDistance = parseInt(distance * 1000,10);
unit = 'm';
}
return numDistance + unit;
} else {
return "?";
}
};
};
*/
Thank you in advance!
Related
I have code that schematically follows the pattern below. The significant part is that there's a parameter declared in the outer function that is later used in the inner one.
function outer(){
var parameter = 3;
this.value = parameter;
$("#something").on("click", function(target){
target.value = parameter / 2;
});
}
In reality, the inner functions are quite a few and rather lengthy so I was hoping to move them out in order to improve readability, like so.
var parameter = 3;
function outer(){
this.value = parameter;
$("#something").on("click", inner);
}
function inner(target){
target.value = parameter / 2;
}
However, what I noticed is that, because of the scoping paradigm of JavaScript, I had to move out the parameter declaration out of the outer function, hence making it global, which to me seems like a disadvantage. (In reality, there are many parameters being used so passing them directly defeats the purpose.)
I can't decide which approach is less flawed. The question is if it's OK to pollute the global scope in order to gain readability or if it's an absolute no-no.
Re your revised question:
The question is if it's OK to pollute the global scope in order to gain readability or if it's an absolute no-no.
It's an absolute no-no. The global namespace is already far, far too polluted. And there's almost never any reason to do it: Instead, you can pollute use a scope that contains all of your code (near-global, if you will) as much as you want:
(function() {
// Our private scope
var lots, of, vars, here;
function outer() {
// ...
}
function inner() {
// ...
}
})();
That at least keeps your variables from truly being globals.
It's still best, though, to keep the scope of variables as constrained as possible. The cool thing is you can repeat the above as necessary to create mini-scopes for common code, nesting them like matryoshka.
Earlier answer before the question revision:
If the question is "what's better," the answer is: Neither. They each have their place, they're useful for different things.
If you're looking for a third solution, you can use partial application (sometimes called currying, though purists have an issue with that). JavaScript doesn't have a built-in partial application feature that doesn't mess with this, but you can easily add one:
(function() {
// Note use of micro-scope here. It's a micro-optimiziation to avoid
// looping up `slice` every time we need it. Mostly it's a justification
// for demonstrating a micro-scope. :-)
var slice = Array.prototype.slice;
Object.defineProperty(Function.prototype, "curry", { // purists: sorry ;-)
value: function() {
var f = this;
var args = slice.call(arguments, 0);
return function() {
return f.apply(this, args.concat(slice.call(arguments)));
};
}
});
})();
Then
function outer(){
var parameter = 3;
this.value = parameter;
$("#something").on("click", inner.curry(parameter));
}
function inner(parameter, target){
target.value = parameter / 2;
}
You've mentioned that there may be a lot of these; if so, you might consider an object with properties instead, so you just curry the object reference rather than a lot of discrete variables.
Example:
(function() {
// Note use of micro-scope here. It's a micro-optimiziation to avoid
// looping up `slice` every time we need it. Mostly it's a justification
// for demonstrating a micro-scope. :-)
var slice = Array.prototype.slice;
Object.defineProperty(Function.prototype, "curry", { // purists: sorry ;-)
value: function() {
var f = this;
var args = slice.call(arguments, 0);
return function() {
return f.apply(this, args.concat(slice.call(arguments)));
};
}
});
})();
function outer() {
var parameter = 3;
setTimeout(inner.curry(parameter));
}
function inner(parameter) {
console.log("Got parameter = " + parameter);
}
outer();
I'm reading this page where it says:
myNameSpace = function(){
var current = null;
function init(){...}
function change(){...}
function verify(){...}
return{
init:init,
change:change
}
}();
Instead of returning the properties and methods I just return pointers
to them. This makes it easy to call functions and access variables
from other places without having to go through the myNameSpace name.
But I don't see how that's true. You still have to do myNameSpace.init() to call init. init() alone doesn't work.
Edit: it occurred to me later that maybe the author meant they were able to call init() without qualification inside the anonymous function. But what stumped me is that the author's previous examples were already able to do that. Specifically, in the immediately foregoing example:
myNameSpace = function(){
var current = null;
function verify(){...}
return{
init:function(){...}
change:function(){...}
}
}();
s/he defined init as s/he was returning it, instead of the example above where s/he defined init first then returned a pointer to it. But in that earlier example, within the anonymous function, if you wanted to call init() without having to do myNameSpace.init(), you already can. So how is the quoted example better?.
Can someone explain? Thanks.
The idea of using a function to clean up scope is, let's say you have a program that looks like this:
var number = 10;
var multiplier = 2;
var endingText = " days left!";
var string = (10 * 2) + endingText;
// string is "20 days left!"
This is an extremely contrived example, but hopefully it's obvious enough that this will declare four variables in the global scope, which is horrible. Let's say what you really want is string, but you still want to keep the other three variables around for whatever reason. You can put them inside an anonymous function, like so:
var string;
(function(){
var number = 10;
var multiplier = 2;
var endingText = " days left!";
string = (10 * 2) + endingText;
})();
// string is still "20 days left!"
Because variables are function scoped, number, multiplier and endingText are NOT declared in the global scope. However, you are still able to use them to get the result that you wanted in the first place.
By the way, you need to wrap parens around a function if you want to immediately invoke it. Also, you should not confuse this with namespacing. Namespacing in JavaScript is the idea of assigning meaningful values to the properties of objects.
var foo = {
hello: "goodbye",
frank: "bob"
};
hello and frank are declared in the foo namespace. That's all there is to it. The example that you posted uses both the namespacing concept and immediately invoking function concept to clean up variables.
The wording is a bit confusing. He meant to say:
Functions and variables can now be easily accessed without a namespace from inside the module
- in contrast to the object literal pattern or the previous example where he put the public methods directly on the exported object. Of course, from outside you always will need to access them as properties of the namespace object - that's the whole point of making it a namespace :-)
For an example, let's fill the functions with a some minimal code:
myNameSpace = function(){
var current = null;
function verify(…){…}
return {
init:function(el){
el.addEventListener("input", myNameSpace.change, false);
// ^^^^^^^^^^^^^^^^^^
},
change:function(){
if (!verify(this.value)) alert("wrong");
}
}
}();
myNameSpace.init(document.getElementById("testInput"));
vs
myNameSpace = function(){
var current = null;
function verify(…){…}
function change(){
if (!verify(this.value)) alert("wrong");
}
function init(el){
el.addEventListener("input", change, false);
// ^^^^^^
}
return {
init:init,
change:change
}
}();
myNameSpace.init(document.getElementById("testInput")); // no difference here
The differences may be minimal in this example, but when you have lots of functions mutually referencing each other it can matter. Also, you would know that all local, namespace-less functions belong to the current module, which massively increases maintainability when dealing with many different namespaces.
Just see the code and tell me what kind of Javascript approach is it?
var Arithmetic = function(){
var obj = {
add: function(a,b) { return a + b; },
multiply: function(a,b) { return a * b; }
};
return obj;
}();
var resultAdd = Arithmetic.add(a,b);
var resultMul = Arithmetic.multiply(a,b);
Why people write the js code in this way....any advantage is there for writing such way.
The above code is related to any design pattern? If yes then tell me the name.
I always write the code like this way and it is easy to understand.
function add(a,b)
{
return a+b;
}
function multiply(a,b)
{
return a*b;
}
and i just call it like this way
var x=add(2,3);
var y=multiply(5,8);
also tell me what is the disadvantage of writing code my way.
The disadvantage to writing code your way is that you put lots of stuff in the global namespace. Imagine what happens when you add your code that defines the add and multiply methods that work on numbers and then include a library that deals with Vectors which also defines the add and multiply methods, but which work on vectors. The methods defined last will overwrite the ones previously defined, breaking some of the code that relies on them.
For this reason, it is preferable to not pollute the global scope and when you have functionality you wish to make available, make it available via a namespace (Arithmetic.add() instead of add()).
If you analize the code a bit, var obj is defined not in the global scope, but in the scope of an anonymous function, so code outside of it can use the obj name for a variable without clashing. The functionality (two methods) is exported to public use by returning an object with the two properties from the anonymous function. Since there is no need for more than one instance of the two methods, the anonymous function returns immediately (http://en.wikipedia.org/wiki/Immediately-invoked_function_expression).
Another advantage to this pattern is that it allows to have private variables:
var uniqueId = function() {
var id = 0;
return function() { return id++; }
}();
uniqueId(); // 0
uniqueId(); // 1
In the example above there is no way to accidentally corrupt the uniqueId function to give bad (non-unique) results because you expose just the functional interface you want, instead of the whole mechanism.
Consider the equivalent in your style:
var id = 0;
function uniqueId() { return id++; };
uniqueId(); // 0
id = 0;
uniqueId(); // 0
The code you gave us is an advanced example of Object Oriented code. I don'r really see the advantage of that encapuslated obj right now, that just makes things difficult to read.
Basically Arithmetic acts as a static class. Without that encapsulated obj and the self-executing function, it may be written like that:
var Arithmetic = {
add: function(a,b) { return a + b; },
multiply: function(a,b) { return a * b; }
}
The code you gave us really does the same - it just doesn't write down that object directly but creates it using that self-executing function (that is a closure, a "function without name", that is called (by adding () to it) immediately after it is created).
The advantage of OO code is not really easy to bring down in a few lines, but regarding to static classes as a collection of methods (as it's done here): it's encapusulation.You can treat each class/object you create as a blackbox and don't have to worry about the details (once it works of course).
The disadvantqage of your "traditional" approach is: It get's corweded once you got many, many functions, and you cannot easily tell which "group" they belong to unless you include thst in your naming conventions (like math_add() or math_mul())
I'm building a library (https://github.com/OscarGodson/storageLocker), a localStorage wrapper to be more exact, but because this is my first try at OO JavaScript I'm still learning and I have a couple questions.
I've seen in other libraries that sometimes they wrap them in a anonymous function. Do I, or should I, do that with this? And if so, how without breaking anything?
For the internal API (basically, the internal functions) how should I write them? Should add them to the main object e.g. storageLocker.prototype.myInternalFunction() or just myInternalFunction() randomly in my script? I didn't want the functions to be global though... One of the functions for example just checks a bunch of items in the JSON, sees if their objects, and then checks what the object type is (like Date()) and then converts it.
How/where should I add global, to my script, vars? e.g. i have a var called patterns that is something like var patterns = {"date":/\/Date\(([0-9]+)\)\//} how should I add that into my script?
Thanks a lot. I want to write my script the right way so im asking you guys. I don't know of any JS guys locally that do any OO JS, they're all old school types...
I'd say:
1) the purpose of this technique is not pollute the global namespace. That is a good thing.
In the example below you can see that all your interaction with the library is via one object MyLibrary. Public API is the return value of the anonymous function.
var MyLibrary = function() {
// private
this.InternalVariable = 'some value';
function internalFunction(x,y) {
return x + y;
}
function getInternalVariable() {
return this.InternalVariable;
}
// public
return {
publicVariable : '1.0',
publicFunction : function(x,y) {
return x + y
},
accessInternalVariable : function() {
return getInternalVariable();
}
}
}();
2) see also the example above on how to place your "internal" functions
3) if you global variable is some kind of a configuration option, I'd just make public setter/getter and kept the variable "private"
http://nefariousdesigns.co.uk/archive/2010/10/object-oriented-javascript-follow-up-part-2-technical/
has a decent section on namespacing worth reading.
http://yuiblog.com/blog/2007/06/12/module-pattern/
is also another good overview.
For more great material on good javascript practices, check out
http://javascript.crockford.com/
After our discussion in the comments, I've changed the example to this:
var storageLocker = function (selector) {
var _selector = selector || "default value";
function myPrivateFunction() {
}
var public = {
get: function () {
return _selector;
},
uppercase : function () {
_selector = _selector.toUpperCase()
return this;
}
}
return public;
};
// use:
var test = storageLocker("search for this").uppercase().get();;
alert(test);
While this isn't exactly an example of a library/module (because you're accessing the code by calling the constructor directly), it is an example of keeping the same object in scope for further chaining of methods. Actually it's not returning the storageLocker object, it's returning the 'public' object, but that object has access to the storageLocker's scope through closure.
There could be other better ways to do this by perhaps returning the storageLocker object itself, but that would require a bit more thinking through.
My understanding of closures is that they are essentially a function which uses a variable that you would assume would be out of scope. I guess heres an example I saw the other day:
function closureMaker(somearg)
{
var local_value = 7;
function funcToReturn(arg1, arg2)
{
return local_value + somearg + arg1 + arg2;
}
return funcToReturn;
}
var myClosure = closureMaker(6); //make the closure
myClosure(2, 3); //using it
Now the closure has local_value and even the original arg, somearg. But I dont get why these are helpful. What is the point of using the 'free' variable local_value or even more unknown to me, why would you use the argument of closureMaking function in your closure function?
I'm more interested in how this is used in javascript, Is this used a lot for AJAX requests and objects?
I got the what. I need the why.
One of the most practical and widely spread usage of closures is to implement private or privileged members for example, for example:
function Test (param) {
var secret = 3;
function privateMethod() {
//...
}
this.publicMember = param;
this.privilegedMember = function () {
return secret * param;
};
}
var foo = new Test(10);
foo.privilegedMember(); // 30
foo.secret; // undefined
The module pattern is also a good example that can use the same principle, e.g.:
var myModule = (function () {
var obj = {}, privateVariable = 1;
function privateMethod() {
// ...
}
obj.publicProperty = 1;
obj.publicMethod = function () {
// private members available here...
};
return obj;
}());
A common run-in is that in a for loop, you want to alert the number of the counter.
function addLinks () {
for(var i = 0; i < 5; ++i) {
var link = document.createElement('a');
link.appendChild(document.createTextNode('Link ' + i));
link.i = i;
link.onclick = function() { alert( i ) };
document.body.appendChild(link);
}
}
addLinks();
When you go to click on these links, it will alert 5 because the loop has already been done and i is equal to 5. We didn't "save" the state of i at the time of execution of the for loop.
We can make a closure to "save" that state:
function addLinks () {
for(var i = 0; i < 5; ++i) {
var link = document.createElement('a');
link.appendChild(document.createTextNode('Link ' + i));
link.i = i;
link.onclick = (function(i) { return function() { alert(i ) } })(i);
document.body.appendChild(link);
}
}
addLinks();
The i is bound to the self executing anonymous functions invoked within each increment in our loop. This way the state is saved and we get the right # on alert.
The example you're looking at is trying to show you how closures work. I think of closures as little pieces of code that you can pass around. The neat thing is that (free) variables in the closure are bound based on the current lexical scope. This is why local_value keeps the value 7 because that's what the value of local_value was when the closure was created.
Javascript implements closures via anonymous functions*, but keep in mind that technically, these are two separate concepts.
In the context of Javascript, closures (implemented as anonymous functions) are very helpful when you want to deal with things that happen asynchronously; a good example is, like you stated, AJAX requests where you cannot predict when you will get a response back from a server. In this case, you have an anonymous function called a callback that you initially define and pass in when you make the AJAX call. When the call successfully completes, your callback is called to process the result. Closures result in cleaner code since you can package behavior and logic inside them. It also helps you abstract the behavior our and separate concerns.
Another use for anonymous functions/closures is for event handling. When an event happens your event handler is called.
Like I had mentioned before, you can abstract behavior and logic and put it in a closure. But what really makes a closure so powerful is context. You can customize the behavior of your closure, depending on the environment in which it was created. This makes your function very versatile, because you are defining its arguments (which will influence its behavior) while you are creating it, instead of when you are calling it (with explicit parameters) during execution.
Here is a good article about closures in Javascript. It's long, but informative:
Javascript Closures
* As CMS mentioned, named functions will behave like anonymous functions because they will have access to variables that are defined in the same lexical scope (or anything up the chain). This is most evident in inner functions. But if you think about it, the same happens for any function; you have access to variables that have been defined in the global scope (i.e., global variables).
This is probably not quite what you are looking for but there is an excellent talk about closures for Java (how they should/could be implemented) that also goes into some examples on where you would want to use them
http://www.youtube.com/watch?v=0zVizaCOhME
Closures are an easy way to make functions that depend on parameters. Or to put it another way, to create a specific instance of a family of functions (read on if that's not clear) depending on some run-time value.
Javascript lets you pass functions around as first-class members; so for example, you could pass around a function that determines how to combine two integers by referring to it directly.
However, going one step further, a closure lets you create a "customised" version of a function, whose exact behaviour depends on some runtime variable (but which otherwise conforms to a framework).
For example, here's a function that will allow a curried addition:
function getAddNFunction(n)
{
function inner(operand)
{
return n + operand;
}
return inner;
}
Now if you call getAddNFunction(7), you get a function that adds 7 to an argument. If you call getAddNFunction(42.5), you get a function that adds 42.5 to the argument.
Hopefully this simple example clarifies the benefit of closures; they allow you to embed arguments in the function at creation time rather than them having to be passed in at execution time (after all, calling getAddNFunction(9)(2) is exactly the same as calling 9 + 2, except for the fact that the two arguments can be supplied at very different times).
So for instance you might want to return some kind of complex XML parsing function relative to some root element; a closure lets you embed that root element definition within the function itself, rather than depend on the caller having access to it whenever they want to execute the function.
If you are comnig from an OO world, closures allow you to create what are essentially private member variables, and methods, for your objects:
function Constructor(...) {
var privateVar = value;
function privateFunc() {
}
this.publicFunc = function() {
// public func has access to privateVar and privateFunc, but code outside Constructor does not
}
}
Douglas Crockford and javascript goodness
In addition to above closure helps in hiding some of the implementation detail.
var Counter = (function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
}
})();
alert(Counter.value()); /* Alerts 0 */
Counter.increment();
Counter.increment();
alert(Counter.value()); /* Alerts 2 */
Counter.decrement();
alert(Counter.value()); /* Alerts 1 */
One more good article
Read this article on module pattern in javascript which heavily uses closures.