Arrays and Functions now how were were taught

In the function lesson we were taught:
const function = () => {}

then in the array lesson we were writing a function in an array like this:
const flowers = [‘peony’, ‘daffodil’, ‘marigold’];

function addFlower(arr) {
arr.push(‘lily’);
}

this function syntax is different and confusing

There are 2 different types of syntax for functions. They are just using the function keyword or using the arrow (=>) syntax.

Functions in whatever form all have four things in common…

  1. A name
  2. A parameter list
  3. A code body
  4. A return value

Declared function

function foo (bar) {
  return bar;
}

Function expression

const foo = function (foo) {
   return bar;
}

arrow function

const foo = (bar) => {
  return bar;
}

The first example is a declaration because it is not written as a statement or assignment. Note the required ‘function’ keyword in the first two. Notice in the last two examples the function expressions are assigned to a variable. That becomes the name we can invoke.

The most common form is the function expression. When assigned to a const variable it cannot be deleted or modified.

The arrow function as written above is a direct equivalent to the function expression. Given a choice between the two, one recommends use the explicit form, not the arrow function.

There are special cases where the arrow function is a simpler choice under the right circumstances, namely when we can implement the concise body function,

const foo = bar => bar;

Note the simplicity given that,

  • parens are removed from a singular parameter
  • curly braces (startbrace, endbrace) are removed
  • implicit return

When it is not possible to use an arrow function in this manner, it makes little to no sense to use the syntax, at all. That should clear up some confusion.