Any reason to have a function as a variable? - javascript

Editing someone else's code, I ran across a pattern I had not previously seen:
var functionName = function functionName(){};
and sometime later, to call the function, using this jQuery
$(functionName);
Now, before I change it to the standard function functionName(){} called with functionName();, is there any reason to do it the other way?
EDIT: Updated to reflect the use of jQuery in the function call. I oversimplified the example. (Oops! Sorry!)

var workerFn = function someDefaultFn() {};
if ( lots of logic) {
workerFn = function specialFn() {};
}
//// later on
workerFn();
So now we have flexibility as to what exactly is invoked. Sort of a poor-man's polymorphism.In your example we'd be passing the workerfn to JQuery to be invoked, so same possibility for flexibility.

The only technical reasons for using a function expression would be to avoid hoisting of the function and/or being able to use another internal name to refer to the function itself.
These are the only differences between function expressions and function declarations and it depends on the context whether they are relevant at all.

I'd say it's a bug because functionName; will not do anything. Or is it a typo in your question?

functionName;
would not call the function. This is just a reference to the function. Calling the function needs the (). So if we have
var functionName = function test(){ alert("0");};
this
functionName;
does not call it. Actually this does not do anything at all (no-op). This is same as
var x;
x;
Only this
functionName()
calls it.
Maybe the functionName; is used for something else. We can tell only if we have context.

[EDIT]
You can find var functionName = function(){}; and make as many instance this way var second = functionName;
It's helpful only if you want to have few variables to call the same function, but with a different param...
But in your case, functionName will contain only that the function functionName() {}; will return.
You propably have something like this in the function content:
var functionName = function test(param) {
[...]
return function(otherParam) {
//do something
};
}

Related

Since function expression and function declaration basically do the same thing, when should I use which?

As the question suggest, when should I use
Example A (function declaration):
function abc(){
// some code
}
abc();
over Example B (function expression):
var abc = function(){
// some code
}
abc();
and vice versa.
I know they are different in nature but they basically just do the same thing (correct me if they're not), right?
So how to I decide which one should I use?
EDIT :
I know for Example A, the function can be called whenever wherever intended due to hoisting.
What I actually want to know is what makes you decide to use Example A or Example B.
If you want to call abc() before defining the function, only the first pattern will work.
The variable declaration does get hoisted, too, but not the assignment, so it will be undefined, whereas the function will already be complete with its body.
I guess I would use the var pattern only if I intend to re-assign it later.
Generally, you should use the function declaration syntax when possible. The best reason is that if you define the function in the code after its use, the code will still work.
stuff();
function stuff() {
console.log("hello");
}
will work, but
stuff();
var stuff = function() {
console.log("hello");
}
will not.
When you are passing an anonymous function to another function, you use a function expression.
doSomething(function() {
console.log("done");
});
Otherwise, both work.

What is the right way of writing an Immediately-Invoked Function Expression in JavaScript? [duplicate]

What are the difference among -
First :-
(function () {
var Book = 'hello';
}());
Second:-
(function () {
var Book = 'hello';
})();
First and second are similar some how in work..
Third :-
(function ($) {
var Book = 'hello';
})(jQuery);
What pattern I need to use and where in my coding.. Third module pattern I have seen while I was reading a article related to backboneJS.
What I understood from Third one "self executing function with the argument “jQuery”" ....
Can any please give me some idea about Immediately Invoked Function Expressions (IIFE).
Thanks !!
In all cases you are doing an anonymous function. I think 1 is the same as 2.
In the third case you are passing jQuery as an argument. This is done when you want to encapsulate jQuery within your function's scope.
For instance, in your application, jQuery var could be jQuery. But within your anonymous function you may want to use it as $.
(function ($) {
//Here jQuery is $
var Book = $(document.body).text();
})(jQuery);
//Out of your function, you user jQuery as jQuery (in this example)
var Book = jQuery(document.body).text();
This is called a closure to avoid conflicts with other libraries such as mootools which are using $. This way you can ensure to use $ in that function with passing jQuery as a param.
(function ($) {
$(function () { // Here in this block you can use '$' in place of jQuery
.......
});
})(jQuery); //<----passing jquery to avoid any conflict with other libraries.
Immediately-invoked function expressions (IIFE) is one of the core JavaScript features. Its main aim is not to clutter the namespaces with disposable functions and variables.
if you use a variable or a function only once, you don't need to make it available for the rest of the code (therefore you make a private access, for example). In case of functions, you may just let them be anonymous, just like the following:
(function(){
console.log("Hello symfony world!");
}());
Please check with this link
Furthermore here is a useful explanatory video in less than 7 minutes
As the other answers pointed out they are all self executing anonymous function or immediate anonymous functions.
The third example is use to create aliases for variables outside the function. This is a good way to prevent name conflicts and creating code where it's possible to easily change a module used in the function. It's essentially a form of dependency injection.
(function (doc, win, $, myModule) {
// Code
}(document, window, jQuery, window.MYAPP.myModule));
doc, win, $ and myModule are injected variables. With this pattern it's trivial to change any of the injected components. Like this
(function (doc, win, $, myModule) {
// Code
}(document, window, jQuery, window.MYAPP.myModule2)); //Use myModule2 instead myModule
Like every other answer has said, in the third function you are passing JQuery to the function.
I would like to take a moment and explain why the first two are the same.
When you create a function, the name of that function is really a function pointer. For instance, in function foo(){}, foo is a pointer to the function that you just made (which explains stuff like this). You dereference that pointer (and thus execute the function) by adding parenthesis at the end of the function name: foo().
So if we look at that code again, in number one, first you create the function:
function () {
var Book = 'hello';
}
And then you dereference it, effectively executing the function: ()
In the second example, you surround the entirety of the function creation in parenthesis:
(function () {
var Book = 'hello';
})
This ensures that you perform the creation operation before your next command, which is to dereference the function again: (). The parenthesis in this case are not really necessary, as the function will be created before it is executed anyway.
All three examples are Immediately Invoked Function Expressions (IIFE).
The only difference is that in the third example jQuery is being passed in as a variable allowing you to use it within the IIFE using its dollar naming convention. e.g.
(function ($) {
var Book = 'hello';
$('#bookelement').html(Book);
})(jQuery);
These all are self executing functions. Now days also known as Immediately Invoked Function Expressions (IIFE).
First two are exactly same with slightly different syntax and third is passing a parameter as jQuery object.
In fact, all three are self executing function's and ti really depends on what you are needing to do.
The only difference between is between 3. 1 and 2 are the same.
The difference with 3 is that you are passing a reference to jquery as an argument. Now all functions inside this annoyomus function have access to jque
All of these are example of self invoking function.
This will give you a clear view:-
var my_func = function(){
var internal_var = "Hello";
return internal_var;
};
var my_func2 = function(name){
var internal_var = "Hello";
return internal_var;
};
var long_var_name = "I can be some object or number or object or array";
var result1 = (my_func());
var result2 = (my_func)();
var result3 = (my_func2)(long_var_name);
console.log(result1, result2, result3);
Using this example you can compare it with the First, Second and Third method.

About function in javascript

Sorry for the rather beginner question. What's the differences of function usage between
$(document).keypress(function() {
//some code
});
and
var somethingElse = function() {
//some code
};
I know the latter is to create a function similar to Java's
public void somethingElse() {
//some code
}
but I always assume the former as anonymous function that act inside a method. Can someone shed me some light regarding this? Thanks.
The first one is a jQuery shortcut to create an event listener.
It's equivalent to:
document.addEventListener('keypress', function() {
// some code
});
More info: http://www.w3schools.com/jsref/met_document_addeventlistener.asp
Now, about named or anonymous functions, what's the difference between
var doSomething = function() {
// some code
};
and this?
function doSomething() {
// some code
}
There's no difference for the developer. Of course there's a difference on memory, but in javascript developers don't have to take care of it.
Actually for the case of an event handler or other techniques that use callback functions, you can pass an anonymous function or a previously declared one, it's exactly the same:
$(document).keypress(doSomething);
or
$(document).keypress(function() {
// some code
});
creates an anon function and passes it to the handler
creates an anonymous function and a variable that references it.
creates a named function - that is hoisted
the hoisted function becomes available to you at any line within your function scope, while the non-hoisted function will be undefined until the line where it is declared runs.
there is no difference between #2 and #3 (other than the hoisting) - some people think that the first one creates an object and the 2nd one is some magical thing, or a global function, but nope - they are both function objects within your scope.
The former is a callback, meaning some instructions that will be executed ONLY as soon as the keypress event in your example is triggered.
Thus, a function's name is not required.
Function expressions, the latter, is mostly used when adding an object's property acting as a method like:
var myObject = {};
myObject.sayHello = function() {
alert("Hello");
}

self executing function jquery vs javascript difference

What are the difference among -
First :-
(function () {
var Book = 'hello';
}());
Second:-
(function () {
var Book = 'hello';
})();
First and second are similar some how in work..
Third :-
(function ($) {
var Book = 'hello';
})(jQuery);
What pattern I need to use and where in my coding.. Third module pattern I have seen while I was reading a article related to backboneJS.
What I understood from Third one "self executing function with the argument “jQuery”" ....
Can any please give me some idea about Immediately Invoked Function Expressions (IIFE).
Thanks !!
In all cases you are doing an anonymous function. I think 1 is the same as 2.
In the third case you are passing jQuery as an argument. This is done when you want to encapsulate jQuery within your function's scope.
For instance, in your application, jQuery var could be jQuery. But within your anonymous function you may want to use it as $.
(function ($) {
//Here jQuery is $
var Book = $(document.body).text();
})(jQuery);
//Out of your function, you user jQuery as jQuery (in this example)
var Book = jQuery(document.body).text();
This is called a closure to avoid conflicts with other libraries such as mootools which are using $. This way you can ensure to use $ in that function with passing jQuery as a param.
(function ($) {
$(function () { // Here in this block you can use '$' in place of jQuery
.......
});
})(jQuery); //<----passing jquery to avoid any conflict with other libraries.
Immediately-invoked function expressions (IIFE) is one of the core JavaScript features. Its main aim is not to clutter the namespaces with disposable functions and variables.
if you use a variable or a function only once, you don't need to make it available for the rest of the code (therefore you make a private access, for example). In case of functions, you may just let them be anonymous, just like the following:
(function(){
console.log("Hello symfony world!");
}());
Please check with this link
Furthermore here is a useful explanatory video in less than 7 minutes
As the other answers pointed out they are all self executing anonymous function or immediate anonymous functions.
The third example is use to create aliases for variables outside the function. This is a good way to prevent name conflicts and creating code where it's possible to easily change a module used in the function. It's essentially a form of dependency injection.
(function (doc, win, $, myModule) {
// Code
}(document, window, jQuery, window.MYAPP.myModule));
doc, win, $ and myModule are injected variables. With this pattern it's trivial to change any of the injected components. Like this
(function (doc, win, $, myModule) {
// Code
}(document, window, jQuery, window.MYAPP.myModule2)); //Use myModule2 instead myModule
Like every other answer has said, in the third function you are passing JQuery to the function.
I would like to take a moment and explain why the first two are the same.
When you create a function, the name of that function is really a function pointer. For instance, in function foo(){}, foo is a pointer to the function that you just made (which explains stuff like this). You dereference that pointer (and thus execute the function) by adding parenthesis at the end of the function name: foo().
So if we look at that code again, in number one, first you create the function:
function () {
var Book = 'hello';
}
And then you dereference it, effectively executing the function: ()
In the second example, you surround the entirety of the function creation in parenthesis:
(function () {
var Book = 'hello';
})
This ensures that you perform the creation operation before your next command, which is to dereference the function again: (). The parenthesis in this case are not really necessary, as the function will be created before it is executed anyway.
All three examples are Immediately Invoked Function Expressions (IIFE).
The only difference is that in the third example jQuery is being passed in as a variable allowing you to use it within the IIFE using its dollar naming convention. e.g.
(function ($) {
var Book = 'hello';
$('#bookelement').html(Book);
})(jQuery);
These all are self executing functions. Now days also known as Immediately Invoked Function Expressions (IIFE).
First two are exactly same with slightly different syntax and third is passing a parameter as jQuery object.
In fact, all three are self executing function's and ti really depends on what you are needing to do.
The only difference between is between 3. 1 and 2 are the same.
The difference with 3 is that you are passing a reference to jquery as an argument. Now all functions inside this annoyomus function have access to jque
All of these are example of self invoking function.
This will give you a clear view:-
var my_func = function(){
var internal_var = "Hello";
return internal_var;
};
var my_func2 = function(name){
var internal_var = "Hello";
return internal_var;
};
var long_var_name = "I can be some object or number or object or array";
var result1 = (my_func());
var result2 = (my_func)();
var result3 = (my_func2)(long_var_name);
console.log(result1, result2, result3);
Using this example you can compare it with the First, Second and Third method.

Assign an already-defined function to a variable with set arguments

I'd like something equivalent to this code, except I don't want my_func to be called when my_var is defined. I want to call my_var() later on in the code with the original argument ('called!') preserved.
function my_func(first_arg) {
alert(first_arg);
};
var my_var = my_func('called!');
How?
Your function will be called when the variable is initialized (and the variable will then hold the output of your function, which isn't what you want). Why not make another function that returns the output of your function?
I'm bad at explaining things, so here's some code to stare at:
var my_var = function() { return my_func('called!'); };
You might be looking for something like Function.prototype.bind, which allows you to bind a function with arguments to a particular context. Basically, it allows you to do this:
function myFunc(firstArg, secondArg) {
alert(firstArg + secondArg);
};
var myVar = myFunc.bind(null, 'called!');
myVar(' - from myVar!');
// result is alert with -> "called! - from myVar"
It's not in older browsers, but the link above has a compatibility implementation to make it work for this particular scenario.
The straightforward way to implement this would be wrapping a call to your function with an argumentless anonymous function:
var my_var = new function() {
my_func('called!');
}
ECMAScript 5th Edition introduces the Function.bind method that implements partial application (or more specifically currying), that would let you write this the following way:
var my_var = my_func.bind(undefined, 'called!');
(The undefined is there because the first parameter of bind() binds a value to the this "parameter".)
Function.bind() is relatively recent and not widely implemented. The Mozilla documentation includes a simple shim you could use to get most of the functionality. John Resig also has a blog post with a different implementation of partial application. It might also be available in one of the many many JS libraries.
Make a new function!
function my_func(first_arg) {
alert(first_arg);
};
var my_var = function() {
my_func('called!');
}
Just need the function to return a function:
function my_func(first_arg) {
return function(){alert(first_arg);}
};
var my_var = my_func('called!');

Categories