It does that so predators will go after the tail instead of it. It's a defense mechanism. Read about it in bio.