The regional laws probably vary.
But there are almost always some general laws against lewd behavior. The details then start to matter. If someone does something lewd in a hidden location/manner such that no one notices, it both won’t be caught and might not amount to a violation.
Many women can (potentially) masturbate without anyone knowing, especially with cover like a restroom stall. That would both generally go unnoticed, not offend anyone since no can even detect it, and depending on local laws might not even be illegal.
In some places, even talking about it might end up being punishable, I suspect (though IANAL). That is, if you say “I’m going to go do erotic things to myself in the bathroom” – that might even be considered punishable lewd behavior.
(As for why someone might want to – each person has their own sexuality, which can vary quite a bit.)