-1

I understand a function, and how it works. However, I am unsure of the following:

 function(msg) { alert(msg); }

If this is not assigned to anything, how is it called?

I am more familiar with this:

function alert(msg) { // set it
   alert(msg);
}

alert('hello!'); //call it
2
  • that first snippet, as-is, causes a syntax error. I think you've left something important off. Commented Nov 26, 2013 at 22:54
  • Ah, I just copied it from a tutorial. Commented Nov 26, 2013 at 23:00

5 Answers 5

2

You can assign functions defined with this syntax to variables, just like other objects:

var myAlert = function(msg) { alert(msg); };
myAlert("hello!");

The most common use case for anonymous functions is as a higher order function - when you provide a function as an argument to another function. A common example is an AJAX request - you provide a callback function to be executed when the request completes. Using jQuery, you could write:

$.get('/someurl', myAlert);

jQuery would execute myAlert when the resource at /someurl responds.

Sign up to request clarification or add additional context in comments.

Comments

1

there are four common ways to call an anonymous function:

save it to a variable like so:

var fn = function(msg) {
   // do something
}

execute by wrapping in parenthesis like so:

 (function(msg) {
    console.log( msg ); // -> 'This is my message'
 })('This is my message');

execute by prepending with an "!"

 !function(msg) {
    console.log( msg ); // -> 'This is my message'
 }('This is my message');

by passing it as a callback

someFn( param1, param1, function( msg ) {
   console.log( msg );
});

6 Comments

How would the callback work, you set 3 parameters? someFn(x, y, z)?
There are more than 4 ways to call an anonymous function, for example: (function(msg){ console.log(msg) }).call(null, 'Hello World');
hey @tmyie it may be a bit beyond the scope of the question but essentially the function would use the first two params for something and call the callback when it wanted to. It could 1 param or twenty it really doesn't matter, it was just to show you another anonymous functions can be used, give me second and I will set up jsfiddle for you
@RobM. this is correct however i didn't see the need to go in to call and apply as it seems they wanted it in context of how they are used in a real world experience, not just any way possible
Fair enough, but they are actually used quite frequently in the real world. Take for instance jQuery's .each method: the fact that you can reference the current DOM node using this within your anonymous function is due to jquery using callback.call(DOMNode, DOMNode, index)
|
0

In addition to assigning it to a variable, as joews points out, you can call it immediately like this:

(function(msg) { alert(msg); })('hello!');

Or you might want to pass it as a parameter to another function, like this:

['hello!'].forEach(function(msg) { alert(msg); });

Comments

0

By itself, it isn't. You need to have some sort of a reference to it.

function(msg) { alert(msg); }();
// alert will appear

var f = function(msg) { alert(msg); };
f();
// alert will appear

$.ajax({
         url: '/some/ajax/url',
         method:' get'
       })
.done(function(msg) { alert(msg); });
// alert will appear displaying the response data.

The idea there is the done function takes a parameter and it executes that parameter, like so:

function done(callback) {
    ...
    callback(responseData);
}

My usage of the jquery ajax api may not be accurate. I did this quickly to illustrate the point.

This pattern is called a function expression by the way, when you pass an inline function to something or assign it to a variable.

Comments

0

must be assigned to a var

For example

var f = function () {};

Or assigned to a arg of function

Fun(arg1, function (){});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.