Anonymous Functions

We've already see examples of named functions, like the following nailPolish() function.

function nailPolish() {
  return("i so pretty");
}

The syntax for named functions is always function nameOf(). Or, if the function takes arguments, function nameOf(argument1, argument2...).

But JavaScript also has functions without names. These are called anonymous functions:

var toothbrush = function() {
  return("i like cleaning");
}

Note that the function keyword is not immediately followed by a name. Rather, we are assigning the variable toothbrush to an anonymous function -- a function without a name. You can tell whether or not a function is anonymous by looking between the function keyword and the parentheses (): If there isn't a name between the function keyword and (), then the function is anonymous. * Named: function name() { ... * Anonymous: var newFunction = function() {...

Anonymous functions can take arguments just like named functions. Here is an example of an anonymous function that takes two arguments:

var adder = function(a, b, c) {
  return(a + b + c);
}
var result = adder(1, 2, 5);
console.log(result); // 8

The variable adder is assigned to a nameless (a/k/a anonymous) function. The anonymous function is invoked with the arguments 1, 2, and 5 and returns the value 8.

Named functions and anonymous functions are used extensively in JavaScript. For reasons you will see, you must be familiar with them both.

Question Click to View Answer

What does the following code print to the console?

var iLike = function(x) {
  return("I like " + x);
}
iLike("pineapples");

I like pineapples

The variable iLike is assigned to an anonymous function that takes one argument and returns a string.

What does the following code print to the console?

var multiply = function(x, y) {
  return(x * y);
}

var r = multiply(10, 3); console.log(r);

30

The multiply variable is assigned to an anonymous function that takes two arguments and returns the product of the arguments.

What does the following code print to the console?

var beHappy = function() {
  console.log("just chill");
}

console.log(beHappy);

function() {
  console.log("just chill");
}

The beHappy variable is assigned to a function. It is a common mistake to forget the parentheses when invoking a function — that is, writing beHappy instead of beHappy(). If you call beHappy without parentheses, the computer returns the function itself rather than its result.

If you want to print the result of the function, you would need to invoke it inside the console.log statement like so:

console.log(beHappy()); // "just chill"
<-- Previous (Variable Scope) Next (Undefined) -->