Function expressions

  • Another way to define a function is by using a function expresison.

  • To define a function expresion we use a function keyword without using a function name

  • Such functions are known as anonymous functions

  • A function expression is often stored inside a variable in order to refer to it

To declare a function expression:

  1. Define a variable with const which is now a common practice since the release of ES6 version of JavaScript

  2. This variable will contain the value of the anonymous function which we define with arguments

  3. Then we put tasks inside the function body with arguments

Example:

const calculateArea = function(height, width) {
    return area = height * width;
}

console.log(calculateArea(5, 4));

// Output: 20

Another example:

const plantNeedsWater = function(day) {
  if (day === 'Wednesday') {
    return true;
  } else {
    return false;
  }
}

console.log(plantNeedsWater('Tuesday'));

// Output: false

Last updated