Masturbation is stimulating the genitalia for the sake of ejaculation. This is prohibited. But if a person was unaware of it being prohibited, then God may overlook this. If ejaculation occurs, then the person enters the state of janabah, and he is required to undertake the ghusl. If he did not do so, the prayers after that will be invalid. If he undertakes ghusl for another reason, e.g. the ghusl of Friday, the state of janabah ends and the prayers after this ghusl are valid until he enters the state of janabah through masturbation again. He will need to repeat those prayers that were invalid because of the failure to do ghusl.