Chapter 3 Cheatsheet: Functions

This cheatsheet summarizes the core concepts of JavaScript functions covered in Chapter 3. Use it as a quick reference when building your logic!

Defining and Calling Functions

Functions are defined using the function keyword and can optionally return a value. JavaScript functions can only return one value (to return multiple, use an Object or Array).

function calculateSum(a, b) {
  return a + b;
}
const sum = calculateSum(5, 10);

Function Hoisting

Functions declared with the function keyword are “hoisted” to the top of their scope during compilation. This allows you to call them before they are defined in the script.

greet(); // This works!

function greet() {
  console.log("Hello!");
}

Scope

JavaScript has four levels of scope:

  1. Global Scope: Accessible everywhere.
  2. Module Scope: Confined to an ES Module file.
  3. Function Scope: var is confined to the function it was created in.
  4. Block Scope: let and const are strictly confined to the block ({}) they are created in (like inside an if statement).

Passing by Value

Primitive types (Numbers, Strings, Booleans) are passed by value. The function receives an independent copy of the data, so modifying the parameter inside the function does not affect the original variable outside.

Default Parameters

You can specify fallback values for optional parameters using =. Always place optional parameters at the end of the parameter list.

function registerUser(email, role = "guest") {
  // role defaults to "guest" if omitted
}

Advanced Function Types

Anonymous Functions Functions without a name, usually passed directly into other functions.

executeTask(function() {
  console.log("Running task");
});

Higher-Order Functions (Functions as Values) Functions can be passed as arguments to other functions.

function applyTwice(value, modifierFunc) {
  return modifierFunc(modifierFunc(value));
}

IIFE (Immediately Invoked Function Expression) A function that is defined and immediately executed. Great for scope isolation.

const result = (function(a) {
  return a * 2;
})(5); // returns 10