Gaining muscle requires a calorie surplus.
Losing fat requires a calorie deficit.
What most people do is cycle. Periods of losing fat (and muscle) and periods of gaining muscle (and fat).
While losing "weight", a significant portion of that weight can be muscle tissue. Doing good quality strength training will help minimise that portion, but you'll almost always be losing *some* muscle if you're "losing weight".
Deb, in New Zealand