Functions, IIFE, and pass-by-value

Like most other programming languages, JavaScript supports abstracting (potentially reusable) chunks of code into “functions”. But additionally, JavaScript also support “lambda expressions”.

Functions

Let’s start with an example:

// function definition
function compare(num1, num2) {
  if(num1 > num2) {
    return 1;
  } else if(num1 == num2) {
    return 0;
  } else {
    return -1;
  }
}

// function calls
const n1 = 6, n2 = 5;
const c1 = compare(n1, n2); // c1 is now 1
const c2 = compare(n1, n1); // c2 is now 0
const c3 = compare(n2, n1); // c3 is now -1

A function:

  1. Is a chunk of code with definite boundaries (begin and end) defined once.
  2. Potentially called any number of times
    • There is a clear distinction between a function definition and a function call.
  3. Has a specific function or responsibilities
  4. Receives zero or more named parameters
  5. Performs some computation (the body of the function)
  6. At some point, the function returns to the execution context of the caller.
  7. The function call and its returned value can be used as part of an expression
  8. It is possible to have functions without names (anonymous functions)
  9. The caller context passes in actual parameter values that get assigned to the formal parameters

Pass-by-value v/s pass-by-reference

  • You can think of the formal parameters as local variables in the function scope. Assigning new values to them doesn’t affect the value of actual parameters. This behavior is called pass-by-value.
  • But there are some scenarios under which it may look like you’re getting pass-by-reference behavior:
function upgradeCustomer(customer) {
  customer.status = "premier";
}
const cust1 = {status: "standard"};
console.log("customer", cust1); // {status: "standard"}
upgradeCustomer(cust1);
console.log("customer", cust1); // {status: "premier"}

This is not pass-by-reference. It is pass-by-value where the value is a reference to an object. You’re changing a property of the object, not the variable itself.

Anonymous Functions and IIFE

JavaScript allows omitting the name of the function:

function() {
  // ... some code
}

This is called anonymous function. There are a few ways to call such a function:

  1. Assign the anonymous function to a variable, and then invoke it:
const f1 = function() {
  // ... some code
};
f1();
  1. Pass the anonymous function as a parameter to another function:
document.addEventListener(function (event) {
  // respond to event
});
  1. Immediately Invoked Function Expression (IIFE):
(function() {
  // ... some code
})();

The wrapping () forces the function definition to take precedence over function invocation.

IIFE is useful because it doesn’t pollute the global namespace.


References:
  1. MDN: Function Expression
  2. MDN: IIFE