HDDs also lose magnetic charge over time, about 1% per year. So you need to periodically spin up and rewrite the data every few years.
CD drives however, can store data indefinitely without needing refreshing.
The important distinction here is that CD-ROMs can store data indefinitely, but CD-Rs and CD-RWs can not.
CD-R media is of limited shelf life as well though
Having had drives which sat for many years and spun right back up without corruption makes me think 1% is too generous maybe 0.05% per year at most
But the materials on the CD eventually break down, sometimes as soon as within 5 years. So you can look into MDisc, which purports 100 years…but only in theory since the tests are just approximations of what would actually happen.