That's an asynchronous call! Use this way:
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
loc = position.coords.longitude;
alert (lat);
});
Background
When you are firing alert(lat), the getCurrentPosition() wouldn't have fired and your value might have not set. If you wanna do something, put it or call it inside that function.
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
loc = position.coords.longitude;
// Something like this.
calculate (lat, loc);
});