One theory is that the stock market is a way for people to invest money in companies. Companies want to raise money to do stuff, so they offer partial ownership of themselves to investors in exchange for money. The companies have projects that they want to fund, the investors want to fund projects, and the stock market is a way of allocating the most money to the best projects.
In its simplest form this theory is not especially true. Most public companies do not fund themselves by selling stock; mostly they fund themselves internally, or with debt, and the main thing that they do with their stock is buy it back. If you buy stock, you are buying it from someone else, who bought it from someone else, who bought it from someone else; way back in the distant past someone bought it from the company, but what does that have to do with you?