Why an LED needs a resistor
An LED drops a nearly fixed voltage, its forward voltage, and above that its current rises very steeply. Without something to limit the current, it overheats and fails. A resistor in series sets the current.
The formula
R = (supply voltage − LED forward voltage) ÷ current
A red LED with a forward voltage of 2.0 V at 20 mA on a 5 V supply needs (5 − 2) ÷ 0.020 = 150 Ω. A white LED at 3.2 V on 12 V needs (12 − 3.2) ÷ 0.020 = 440 Ω; use the next standard value up, 470 Ω.
Typical forward voltages are about 1.8 to 2.2 V for red, yellow and orange, and about 2.8 to 3.4 V for blue, white and most green LEDs. The datasheet gives the exact figure.
Power rating
The resistor turns the extra voltage into heat: P = I² × R. For the 150 Ω example, 0.02² × 150 = 0.06 W, so a common 0.25 W resistor is fine. Choose a rating at least double the calculated power.
Several LEDs
In series, add the forward voltages and use one resistor, as long as the total stays below the supply. In parallel, give each LED its own resistor, because small differences between LEDs make them share current unevenly.
Calculator
The LED Resistor Calculator gives the exact value, the nearest standard value and the power. For other circuits, the Ohm's Law Calculator and the Series and Parallel Calculator do the rest.