I've worked with many excellent programmers over 40, some over 70. You might want to look for companies that are run by older folk, and maybe in more established companies.
Anecdotally, I haven't seen a lot of 40+ engineers in Silicon Valley, but here in San Diego I've never met a Qualcomm engineer under 40. Maybe geography has something to do with it.