I totally understand the sentiment of writing elegant code that lasts forever, but I think developers need to manage their expectations a little better.
If you're writing foundational code for an operating system, then yeah, whatever you write is going to stick around for a while. (Which means you need to be a LOT more careful about what you write.)
If you're writing code for a mobile app or website, expect your code to get thrown out in a few months due to shifting requirements. I'm sure the Facebook app has been completely rewritten more than once, since they switched to React Native at one point.
If you're writing a JavaScript library, expect your code to be replaced next week. :D