Functions: Declarations, Expressions & Arrows

The building blocks of JavaScript. Learn the three ways to write functions, how they receive data, and how they return results.

JavaScript7 min readConcept 12 of 62

What is a function?

A function is a reusable block of code designed to perform a particular task. You define it once, and you can 'call' or 'invoke' it as many times as you want.

Functions take inputs (called parameters), do some work, and then output a result (via the return keyword).

The three ways to write them

1. **Function Declarations**: function add(a, b) { ... }. These are 'hoisted', meaning you can call them before they appear in the code.

2. **Function Expressions**: const add = function(a, b) { ... }. Here, the function is anonymous and assigned to a variable. It is not hoisted.

3. **Arrow Functions**: const add = (a, b) => { ... }. Introduced in ES6, these are shorter and have special rules regarding the this keyword (which we will cover in advanced topics).

Parameters vs. Arguments

These terms are often mixed up, but they mean different things.

**Parameters** are the variables listed in the function's definition. For example, in function greet(name), name is the parameter.

**Arguments** are the actual values you pass to the function when you call it. In greet('Alice'), 'Alice' is the argument. The argument binds to the parameter when the function runs.

The Function Flow

Watch how arguments flow into a function's parameters, get processed, and then flow back out via the return statement.

The Data Flow

// 1. The Function Definition (Parameters)
function calculateTotal(subtotal, taxRate) {
const tax = subtotal * taxRate;
return subtotal + tax;
}
// 2. The Function Call (Arguments)
const total =calculateTotal(50, 0.1);

Under the hood

The function is defined in memory, waiting to be called.

iWhen a function executes a return statement, it instantly exits. Any code written beneath the return inside that function will never be reached!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1Which type of function is 'hoisted' to the top of its scope, allowing you to call it before it is defined?
  2. 2In the code `multiply(5, 10)`, what are `5` and `10` called?
  3. 3What does a function return if there is no `return` keyword used inside it?

Remember this

  • Function Declarations are hoisted; Expressions and Arrow Functions are not.
  • Parameters are the names in the definition; Arguments are the values passed during the call.
  • Functions without a return statement implicitly return undefined.
  • Arrow functions offer a concise syntax and can implicitly return values if written on one line.

Done with this concept?

Mark it complete to track your progress. No login needed.