A detached HEAD state happens when Git's HEAD points directly to a specific commit instead of to a branch, meaning any new commits you make aren't attached to any branch and can be lost if you switch away carelessly.
Key Points: • It commonly occurs when you check out a specific commit hash or a tag directly, rather than a branch name. • In this state, Git still lets you make commits, but they only exist as long as something references them, since no branch pointer moves forward with you. • If you switch to another branch without saving your work, those "floating" commits become unreachable and are eventually garbage collected. • git status warns you explicitly when you're in a detached HEAD state, which is a useful signal to pay attention to. • To preserve any work made in this state, create a new branch pointing at the current commit with git checkout -b before doing anything else.
Example: A developer runs git checkout a1b2c3d to inspect an old commit, makes a small fix, and forgets they're in detached HEAD; without creating a branch first, switching back to main would leave that fix orphaned and eventually eligible for garbage collection.
Code Example:
git checkout a1b2c3d
# realize you need to keep changes made here
git checkout -b rescue-branchInterview Tip: A concise interview answer is:
"Detached HEAD happens when you check out a specific commit or tag instead of a branch, so HEAD points directly at that commit rather than moving with a branch. Any commits made there aren't attached to a branch, so I always create a new branch first if I need to keep that work."