Branching & Merging
Work on features in isolation with branches, then combine them back with merges
Branches are Git's superpower. They let you build a feature, try a risky idea, or fix a bug in complete isolation — without touching the working code everyone else depends on. When it's ready, you merge it back.
What Is a Branch, Really?
A branch is just a movable pointer to a commit. That's it. Creating one doesn't copy files — it writes a tiny reference. This is why Git branching is instant and cheap, unlike older tools where a "branch" meant duplicating the whole project.
main ─── A ─── B ─── C ← main points here
↖
feature ──────────────── D ← feature points here
HEAD is a special pointer that tells Git which branch you're currently "on". Commits you make move the current branch pointer forward.
Creating and Switching
The modern command is git switch:
git switch -c feature/login # create a new branch AND switch to it
git switch main # switch back to an existing branch
git branch # list branches (* marks the current one)
main
* feature/login
You'll see git checkout -b in older tutorials — it still works. Modern Git
split its jobs into two clearer commands: git switch (change branches) and
git restore (undo file changes). Prefer them.
Making Commits on a Branch
Once on feature/login, commits land on that branch only. main stays frozen where it was:
git switch -c feature/login
# ...edit files...
git add .
git commit -m "feat(auth): add login form"
main is untouched — your teammates keep working on it, unaware of your in-progress feature.
Merging Back
When the feature is done, switch to the branch you want to merge into (usually main), then merge:
git switch main
git merge feature/login
There are two ways this plays out:
Fast-forward — if main hasn't changed since you branched, Git just slides the main pointer forward. No new commit needed.
before: main → A feature → A─B─C
after: main ─────────────→ C (fast-forward)
Merge commit — if main has moved on (someone else committed), Git creates a new commit that ties the two histories together.
main ─── A ─── B ─────── M ← merge commit M
↖ ↗
feature ────────── C ── D
After merging, delete the branch — its work now lives in main:
git branch -d feature/login
When Conflicts Happen
If the same lines were changed on both branches, Git can't decide which version wins and pauses with a merge conflict. This is normal and expected on real teams — we cover exactly how to resolve them in the next lesson.
Teams commonly prefix branches by purpose: feature/, fix/, chore/. A
name like fix/cart-total-rounding tells everyone what the branch is for at
a glance.