Around 1 out of 200 dogs gets infected with heartworm disease each year from being bitten by mosquitoes.
That amount of dogs that get heartworm each year translates into 250,000 out of 50,000,000 dogs that get heartworm so it's not very likely that your dog will get heartworm.
If your dog has been bitten by a mosquito though then you need to give them heartworm medicine to kill off the heartworm before it starts.
Giving a dog heartworm medicine doesn't prevent the dog from getting heartworms but instead the heartworm medicine kills the heartworm larvae that is already inside your dog.
So if you dog hasn't been infected with heartworms then it's actually harmful to give your dog heartworm medicine on a regular basis when they don't have heartworms.
The way dogs get infected with heartworms is from mosquitoes.
When a mosquito bites a dog then that's how they can get infected with the heartworm so if they haven't been bitten by a mosquito then they won't get heartworm.