It's not really an or. An investment and a purchase are 2 different things.
It's not really 40k either, it's a matter of cost of capital.
You can trade on margins or go with options, you can do lease/loan with a car.
Is the car a necessity, what's the cost of ownership, including the cost of capital.
On the investment side, there is a risk and reward.
If you need a car, Model 3 at 40k sticker price is not that expensive to own at all. Is it the right car for you, can you afford it, that will depend and you don't need 40k to acquire it.
Is the stock a good investment, can you more than cover the costs of a loan. If you invest your capital for decent returns,, it's likely better to not waste it on big purchases and go with leasing or loan.
You only need a few k$ to acquire both the car and options that are the equivalent of 40k$ in stock- risk is minimal in this scenario, a few k lost.