You should check that loc isn't null, or if it is a turf (istype checks will return false if it is null).