JavaScript Functions

Functions are objects in JavaScript and can be used as variables in expressions, passed to other functions, or treated like numbers or strings.

The traditional function declaration has several parts:

  • function keyword;
  • name of the function;
  • function body, which contains JavaScript statements; and
  • return statement

Functions may have "parameters", values passed to the function from a calling program, but they are not required. To execute a function, it must be "called". This will run the statements in the body of the function. Read this article about how functions are defined and used. After reading this article, consider these questions: 

  • What is the difference between local, global, and lexical scoping?
  • Can functions be called with different numbers of parameters?
  • What is returned if a function does not have a "return" statement?

Nested scope

JavaScript distinguishes not just global and local bindings. Blocks and functions can be created inside other blocks and functions, producing multiple degrees of locality.

For example, this function - which outputs the ingredients needed to make a batch of hummus - has another function inside it:

 const hummus = function(factor) {
  const ingredient = function(amount, unit, name) {
    let ingredientAmount = amount * factor;
    if (ingredientAmount > 1) {
      unit += "s";
    }
    console.log(`${ingredientAmount} ${unit} ${name}`);
  };
  ingredient(1, "can", "chickpeas");
  ingredient(0.25, "cup", "tahini");
  ingredient(0.25, "cup", "lemon juice");
  ingredient(1, "clove", "garlic");
  ingredient(2, "tablespoon", "olive oil");
  ingredient(0.5, "teaspoon", "cumin");
};

The code inside the ingredient function can see the factor binding from the outer function. But its local bindings, such as unit or ingredientAmount, are not visible in the outer function.

The set of bindings visible inside a block is determined by the place of that block in the program text. Each local scope can also see all the local scopes that contain it, and all scopes can see the global scope. This approach to binding visibility is called lexical scoping.