Input (x)
1
double(x)
Output
?
function double(x) {
    return x * 2;
}

// Input: 1 -> Output: 2

The Function Machine

A function is a modular, reusable block of code that performs a specific task. Some calculate values (like a calculator), while others perform actions.

Anatomy of a Function

Let's break it down. 'function' is the keyword. 'cook' is the name. '()' holds parameters. '{ ... }' holds the code body.

Parameters

Parameters are the settings or dials on the machine. 'Sugar' and 'Milk' are parameters. When we call the function, we give them values.

The 'return' Keyword

The 'return' keyword serves two purposes: it STOPS the function immediately, and it sends a value back to the place where the function was called.

Void Functions (Side Effects)

Not all functions return a value! Some just do work, like logging to the console or changing the screen color. These return 'undefined'.

Function Expressions

Functions are values! You can store them in variables (const myFunc = ...). This is called a Function Expression.

Arrow Functions

Modern JavaScript (ES6) introduced a shorter way to write functions using the '=>' arrow. It's concise and great for small tasks.

I.I.F.E.

Immediately Invoked Function Expression. A function that runs the moment it's defined. wrapped in () and called with ().

The 'new' Keyword

Used to create a new instance of an object from a Constructor Function. It links the new object to the function's prototype.

The 'this' Keyword

Who called me? 'this' refers to the object that is executing the current function. It gives functions context.

Function Factory

You've mastered the building blocks of logic!
With Functions, you can now organize and reuse your code like a pro.

AlgoAnimator: Interactive Data Structures