The purposes behind the OT Law are various and complex and often debated. But one of its main functions is articulated beautifully by my favorite theologian (Herman Bavinck) writing in an often overlooked, but outstanding, volume on theology (Our Reasonable Faith). These are his words on page 81:
So far from being opposed to the promise, the law serves precisely as the means in God’s hand to bring the promise constantly nearer to its fulfillment. The law put Israel under restrictions, as a prisoner is put under restraint and denied the freedom of movement. Like a ‘pedagogue’ the law took Israel by the hand, accompanied her always and everywhere, and never for a moment left her out of its sight. As a guardian and supporter, the law maintained a strict watch over Israel in order that Israel might learn to know and to love the promise in its necessity and its glory.
Without the law, so to speak, the promise and its fulfillment would have come to nothing. Then Israel would quickly have fallen back into paganism, and would have lost both her revelation of God with its promise and her own religion and her place among the nations.
But now the law has fenced Israel in, segregated her, maintained her in isolation, guarded her against dissolution, and has thus created an area and defined a sphere in which God could preserve His promise purely, give it wider scope, develop it, increase it, and bring it always closer to its fulfillment. The law was serviceable to the fulfillment of the promise. It placed everybody under the wrath of God and under the sentence of death, it comprehended everybody within the pale of sin in order that the promise, given to Abraham and fulfilled in Christ, should be given to all believers, and that these all should attain to the inheritance as children (Gal. 3:21 and 4:7).