Branching Basics

Branching is Git's most powerful feature. It allows you to diverge from the main line of development and continue to do work without affecting that main line. In Git, branching is incredibly lightweight and fast—creating a new branch is nearly instantaneous, and switching between them is just as quick.


1. What is a Branch?

To understand branching, you must understand how Git stores data. A Git branch is not a copy of your files; instead, it is a lightweight, movable pointer to a specific commit. The default branch name in Git is usually main.

When you make a commit, Git stores a snapshot of your files and a pointer to the previous commit (the "parent"). Your current branch pointer then automatically moves forward to point to this new commit.

The HEAD Pointer: "You Are Here"

Git keeps a special pointer called HEAD. This is a pointer to the local branch you're currently working on. Think of it as the "YOU ARE HERE" sticker on a map.

mainHEAD


2. Creating a Branch

When you create a new branch, Git simply creates a new pointer at the same commit you're currently on. It does not create a new set of files.

git branch feature-login

At this stage, both main and feature-login point to the same commit, but HEAD is still pointing to main.

mainfeature-login


3. Switching Branches

To start working on your new branch, you must "switch" to it. This moves the HEAD pointer to the new branch.

# The modern way (Git 2.23+)
git switch feature-login

# The traditional way
git checkout feature-login

Now, any new commits you make will only move the feature-login pointer forward. The main branch stays exactly where it was.

Visualizing Divergence

After making a new commit on your feature branch, the pointers diverge:

mainfeature-loginHEAD


4. Why Use Branches?

Branching allows you to work in a "sandbox" environment.

  • Stable Main Branch: Your main branch always contains code that is tested and ready for production.
  • Experimental Features: You can create a branch for a risky idea. If it fails, you just delete the branch without ever touching your working code.
  • Parallel Work: Multiple developers can work on different features (e.g., feature-auth, fix-css-bug) simultaneously. Each person has their own branch and their own HEAD.

5. Branch Management Commands

ActionCommand
Creategit branch <name>
Switchgit switch <name>
Create & Switchgit switch -c <name>
List Localgit branch
List Allgit branch -a
Deletegit branch -d <name>
Force Deletegit branch -D <name>

Pro Tip: Keep your branches small and focused. Instead of one giant "feature" branch, create several smaller branches (e.g., feature-ui, feature-api). This makes them much easier to review and merge later.

In the next chapter, we'll learn how to bring these divergent lines of development back together using Merging.