JavaScript Introduction

Download JavaScript for free

Example

In JavaScript, functions may be anonymously defined using the "arrow" (=>) syntax, which is sometimes referred to as a lambda expression due to Common Lisp similarities.

The simplest form of an arrow function has its arguments on the left side of => and the return value on the right side:

item => item + 1 // -> function(item){return item + 1}

This function can be immediately invoked by providing an argument to the expression:

(item => item + 1)(41) // -> 42

If an arrow function takes a single parameter, the parentheses around that parameter are optional. For example, the following expressions assign the same type of function into constant variables:

const foo = bar => bar + 1;
const bar = (baz) => baz + 1;

However, if the arrow function takes no parameters, or more than one parameter, a new set of parentheses must encase all the arguments:

(() => "foo")() // -> "foo"

((bow, arrow) => bow + arrow)('I took an arrow ', 'to the knee...')
// -> "I took an arrow to the knee..."

If the function body doesn't consist of a single expression, it must be surrounded by brackets and use an explicit return statement for providing a result:

(bar => {
  const baz = 41;
  return bar + baz;
})(1); // -> 42

If the arrow function's body consists only of an object literal, this object literal has to be enclosed in parentheses:

(bar => ({ baz: 1 }))(); // -> Object {baz: 1}

The extra parentheses indicate that the opening and closing brackets are part of the object literal, i.e. they are not delimiters of the function body.

Arguments Object