Tolkien started writing the legendarium to support his constructed languages, then came The Hobbit, a children's story with the lengendarium as its (distant) background. The publishers of The Hobbit asked Tolkien to work on a sequel and that's what became The Lord of the Rings.
The legendarium is what Christopher Tolkien edited together to form The Silmarillion.
If I recall correctly, J.R.R.Tolkien loved both Welsh and Finnish and tried to construct a linguistic history that would explain a Welsh-like and Finnish-like language (Sindarin and Quenya respectively) that had a common origin.