Generally, you forfeit all contributions that haven’t vested. “Vesting” means that you own the contributions. Your contributions, pretax and Roth, are always 100% vested. But your 401(k) plan may generally require up to six years of service before you fully vest in employer matching contributions (although some plans have a much faster vesting schedule).
When you terminate employment, you can generally leave your money in your 401(k) plan until the plan’s normal retirement age (typically age 65), or you can roll your dollars over tax free to an IRA or to another employer’s retirement plan.