Write code you can reuse
A JavaScript function is a reusable block of code that performs a particular task. You write it once and can use it whenever you need it — here you'll learn how to create a function, pass information into it, calculate a result, and display it on a webpage by building a temperature converter.
- 1Learn
- 2Practice
- 3Test
- 4Build
0 of 6 topics complete
Learn JavaScript functions
Put it together
Build a temperature converter using a JavaScript function. Enter a Celsius value, run the code, and watch it convert to Fahrenheit.
Interactive temperature converter
A practical JavaScript function exercise. Pick a conversion, enter a temperature, and watch the function calculate the result.
Formula: (68 − 32) × 5 ÷ 9
JavaScript functions
A function is a reusable block of code that performs a particular task. You write it once and can call it whenever you need it.
Basic function syntax
// Define the function
function toCelsius(fahrenheit) {
return (fahrenheit - 32) * 5 / 9;
}
// Call the function
let temperature = toCelsius(68); // 20
console.log(temperature);
Common temperature formulas
| Conversion | Formula | Example |
|---|---|---|
| Fahrenheit to Celsius | (f - 32) * 5 / 9 |
68°F → 20°C |
| Celsius to Fahrenheit | (c * 9 / 5) + 32 |
20°C → 68°F |
| Celsius to Kelvin | c + 273.15 |
20°C → 293.15 K |
Key parts of a function
Define the function
Create a named function with the function keyword.
function toCelsius(fahrenheit) { ... }
Calculate the temperature
Use return to send the answer back.
return (fahrenheit - 32) * 5 / 9;
Call the function
Pass a value in and get a result back.
toCelsius(68); // 20