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.