mindixx
mindixx

Reference · module 2

Functions

Everything this module explains, on one page.

function and return

Write a function that takes values and gives a result back.

  • function greet(name) { ... } creates a function called greet with one parameter, name. Nothing runs yet: the body inside the braces runs only when you call greet("Ana").
  • Parameters are names for the values a call passes in. In greet("Ana") the parameter name holds "Ana"; in greet("Bo") it holds "Bo". Each call gets its own values.
  • return sends a value back to where the function was called and ends the function at once. A function without return gives back undefined.

The mistake you are about to make

function double(n) { console.log(n * 2); }

function double(n) { return n * 2; }

The number shows up in the console, so it looks returned. console.log only prints: const x = double(4) gets undefined, and nothing can be calculated with it.

Arrow functions

Read and write the short arrow form that most modern code uses.

  • const add = (a, b) => { return a + b; }; is an arrow function: the same kind of function as before, stored in a variable. You call it the same way, add(2, 3).
  • When the body is a single expression, drop the braces and return: const add = (a, b) => a + b; returns a + b by itself. With exactly one parameter the brackets are optional too: n => n * 2.
  • A function is a value like a number or a string. You can store it in a variable, pass it to another function and call it there — which is exactly how array methods work later.

The mistake you are about to make

const double = n => { n * 2 };

const double = n => n * 2;

The braces look like harmless wrapping. With them the arrow stops returning by itself: it needs return, or double(4) gives undefined.

Defaults, scope and templates

Give parameters defaults, know where a variable lives, and build text with templates.

  • A parameter can have a default: function greet(name = "friend") uses "friend" when the call passes nothing. greet() and greet(undefined) both get the default.
  • Variables declared inside a function exist only there. A const total inside calc cannot be read after calc finishes; outside, the name total means nothing.
  • Backticks make template literals: `Hi, ${name}!` puts the value of name inside the text. Any expression fits in ${}, so `${a} + ${b} = ${a + b}` works too.

The mistake you are about to make

"Hi, ${name}!"

`Hi, ${name}!`

Double quotes and backticks look almost the same and are interchangeable elsewhere. Only backticks understand ${}: inside double quotes you get the literal text ${name}.

Back to the map