In basic terms, ignoring certain situations like being significantly overweight or being completely untrained, you build muscle (and add some fat) during a caloric surplus, and you lose fat (and a bit of muscle) while being in a caloric deficit.
Naturally, it's logically impossible to simultaneously be in a caloric surplus and deficit. It's not possible to build a large amount of muscle while also being in a caloric deficit, and you won't ever lose a meaningful amount of fat without being in a deficit.