RE: Populate a many to many subgrid inside a form using Javascript
you have two ways depending on the relationship.
1) if the relationship is 1:N (like account-contact with parentcustomerid) you can update the records you want to associate with just the main ID (you can use Xrm.WebApi.updateRecord for example)
2) if the relationship is N:N you must use the associate method
(to be 100% precise, you can also use the associate method when you have a 1:N relationship, but is a preference as the result is the same)
to generate the code you can use the tool Dataverse REST Builder (link in my signature) and if you use the associate method with Xrm.WebApi you can actually associate multiple records with a single request (by adding the records inside the relatedEntities property) if you use another JavaScript syntax (fetch, jquery, xhr) you must associate the records one by one
hope it helps