PROJEXSIMPLE
JavaScript Functions

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.

  1. 1Learn
  2. 2Practice
  3. 3Test
  4. 4Build

0 of 6 topics complete

0% Complete
0 Lessons done
0 Points
Lessons

Learn JavaScript functions

Build

Put it together

Build a temperature converter using a JavaScript function. Enter a Celsius value, run the code, and watch it convert to Fahrenheit.

Preview
Try it live

Interactive temperature converter

A practical JavaScript function exercise. Pick a conversion, enter a temperature, and watch the function calculate the result.

Converted temperature
20 °C

Formula: (68 − 32) × 5 ÷ 9

JavaScript Functions

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

1

Define the function

Create a named function with the function keyword.

function toCelsius(fahrenheit) { ... }
2

Calculate the temperature

Use return to send the answer back.

return (fahrenheit - 32) * 5 / 9;
3

Call the function

Pass a value in and get a result back.

toCelsius(68); // 20