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?

Summary

This chapter taught you how to write your own functions. The function keyword, when used as an expression, can create a function value. When used as a statement, it can be used to declare a binding and give it a function as its value. Arrow functions are yet another way to create functions.

 // Define f to hold a function value
const f = function(a) {
  console.log(a + 2);
};

// Declare g to be a function
function g(a, b) {
  return a * b * 3.5;
}

// A less verbose function value
let h = a => a % 3;


A key aspect in understanding functions is understanding scopes. Each block creates a new scope. Parameters and bindings declared in a given scope are local and not visible from the outside. Bindings declared with var behave differently - they end up in the nearest function scope or the global scope.

Separating the tasks your program performs into different functions is helpful. You won't have to repeat yourself as much, and functions can help organize a program by grouping code into pieces that do specific things.