← Web basics: HTML, CSS and JavaScript

Functions

Name a piece of code, give it inputs, and get a result back.

Start this lesson

A function is a reusable recipe. You write it once with function, a name, parameters in parentheses (the inputs), and a body in curly braces. Inside, return hands a result back to whoever called it. Then you call the function by name with real values, as many times as you like. Functions keep code short and let you give a clear name to an idea, like tipFor or isWeekend.

function toCelsius(fahrenheit) {
  return (fahrenheit - 32) * 5 / 9;
}

toCelsius(212);   // 100
toCelsius(50);    // 10

const square = (n) => n * n;   // a shorter "arrow function"
square(6);        // 36

fahrenheit is the parameter: a placeholder that takes whatever value is passed in. return sends the answer back. The arrow function at the end does the same kind of job in a shorter form.

return is not the same as console.log. console.log only shows a value to the programmer; return gives the value to the code that called the function so it can be used.

A function stops as soon as it reaches return. Code after it in the same block does not run.