Creating & Switching Branches

How to use `git branch` to create pointers and `git switch` to move your HEAD cursor.

Version Control5 min readConcept 9 of 29

Creating and Switching Branches

git branch <name> is the command used to create a new branch. In Git, creating a branch simply creates a new text file containing the hash of the current commit—it's just a new pointer.

git switch <name> (or git checkout) is used to change the currently active branch. git switch was recently introduced to explicitly handle changing branches without the confusing secondary functions (like reverting files) that git checkout possesses.

Why it matters

Web developers often work on multiple things simultaneously (e.g., building a new navigation bar, fixing a footer bug).

Branches allow a developer to create a safe 'sandbox' to work on a new feature in isolation without breaking the stable main branch. Once the feature is complete and tested, the branch can be merged back into main.

How it works

Git tracks your current active branch using a special pointer called HEAD. When you run git switch <branch-name>, Git moves the HEAD pointer to attach it to the specified branch.

Git then magically updates the files in your working directory to match the exact snapshot of the commit that branch points to.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What does the `git switch` command actually do under the hood?
  2. 2Why did Git introduce the `git switch` command when `git checkout` already existed?
  3. 3If you are currently on the `main` branch and run the command `git branch new-layout`, what happens?

Remember this

  • git branch <name> creates a new branch pointer but DOES NOT switch you to it.
  • git switch <name> moves HEAD to a branch and updates your working directory.
  • Use git switch -c <name> to create and switch in one command.

Done with this concept?

Mark it complete to track your progress. No login needed.