Web Programming/JavaScript/Nodejs

From Wikibooks, open books for an open world
Jump to navigation Jump to search

code between curly braces is also known as a block.

A function expression is similar to function declaration, with the exception that identifier can be omitted, creating an anonymous function.

const square = function (number) {
  return number * number;
};

Arrow function syntax is a shorter syntax for a function expression.

const square = (number) => {
  return number * number;
};

We can refactor an arrow function in three ways. The most condensed form of the function is known as concise body.

  1. Functions that take a single parameter should not use parentheses. The code will still work, but it's better practice to omit the parentheses around single parameters. However, if a function takes zero or multiple parameters, parentheses are required.
  2. A function composed of a sole single-line block is automatically returned. The contents of the block should immediately follow the arrow => and the return keyword can be removed. This is referred to as implicit return.
  3. A function composed of a sole single-line block does not need brackets.

In a concise body:

const square = number => number * number;