Exposure to ambient air pollution has been associated with reduced cognitive function in childhood and later life, with too few mid-life studies to draw conclusions. In contrast, residential greenness has been associated with enhanced cognitive function throughout the lifecourse. Here we examine the extent to which (1) ambient air pollution and residential greenness predict later cognitive function in adolescence and mid-life, and (2) greenness modifies air pollution-cognitive function associations. Participants: 6220 adolescents (51% male) and 2623 mid-life adults (96% mothers) from the Longitudinal Study of Australian Children. Measures: Exposures: Annual average particulate matter <2.5 μm (PM2.5), nitrogen dioxide (NO2) and greenness (Normalised Difference Vegetation Index) for residential addresses from validated land-use regression models over a 10–13-year period. Outcomes: Cognitive function from CogState tests of attention, working memory and executive function, dichotomised into poorer (worst quartile) versus not poor. Analyses: Adjusted mixed-effects generalised linear models with residential greenness assessed as an effect modifier (high vs. low divided at median). The annual mean for PM2.5 and NO2 across exposure windows was 6.3–6.8 μg/m3, and 5.5–7.1 ppb, respectively. For adolescents, an IQR increment of NO2 was associated with 19–24% increased odds of having poorer executive function across all time windows, while associations weren't observed between air pollution and other outcomes. For adults, high NO2 predicted poorer cognitive function across all outcomes, while high PM2.5 predicted poorer attention only. There was little evidence of associations between greenness and cognitive function in adjusted models for both generations. Interactions were found between residential greenness, air pollutants and cognitive function in adolescents, but not adults. The magnitude of effects was similar across generations and exposure windows. Findings highlight the potential benefits of cognitive health associated with the regulation of air pollution and urban planning strategies for increasing green spaces and vegetation.