I had a D5300 I upgraded from a D40x and it was a nice easy transition, but since then - have upgraded to a D7500 for weather sealing and better button placement. I decided to go with the D5300 in lieu of the D5600 because I didn't think I needed a touch screen. I quickly found out that I wanted to control shutter speed, aperture and ISO with easily accessible dials and buttons on the camera rather than trying to find them in the menu. Good bye D5300, hello D7500.
The only thing that I really miss about the D5300 is the screen, the sideways flip out screen is the best in the industry but I assume since Canon still has it but no Nikon does, Nikon must have gotten in trouble for using that design and went to their current flip screen instead- tilting up and down only. Not bad, not great either. One way around this is the new Snapbridge. Worked ok on the D5300,(with limitations) but is much better on the D7500 and it allows you to use your phone to see what the camera does as well as adjust settings like ISO, shutter speed and aperture, as well as focusing and taking the shot. These are all things that are not offered on the D40 and kind of need to be experienced first hand to see if they're important to you or not.
There's no perfect choice. They all have trade offs. If price is most important, go with what you can afford and live with the limitations. If weather sealing is most important and ease of manipulating settings, the 3xxx and 5xxx are out and you should look at the D7500,( or D7200 for an older model with the less refined snapbridge).
Another nice thing about the 7xxx is you can use older lenses that are still amazing. The D7500 will still shoot the "d"lenses that have the screw drive focus because there is a focus motor in the camera. The D3xxx and D5xxx as such with the D40 do not have a focus motor in the camera. The lenses are a bit slower to focus and a bit more noisy, but if you were trying to invest in glass later down the road, the screw drive lenses are much cheaper than the current counterpart, ( a couple hundred for a 80-200 f2.8D as opposed to a couple thousand for a 70-200 f2.8 af-s, a couple hundred for a 35-70 f2.8D vs 5 times that amount for a 24-70 f2.8 af-s). So if you need new glass too, keep that in mind. Hope this helps.