So far all your commits live on a single line of history called main (older repos used master — same idea). Branches let you split off a separate line of work without affecting main.
Why Branches?
Imagine you're building a blog and main works perfectly. You want to try a dark-mode redesign but you're not sure it'll look good. Instead of risking main, you create a branch:
- main — stays stable, always deployable
- dark-mode — your experiment; if it fails, delete the branch and main is untouched
Branches are cheap in Git. Creating one takes milliseconds. Professional teams use them constantly.
See Your Current Branch
git branch
Output:
* main
The asterisk shows which branch you're on.
Create and Switch to a Branch
git switch -c dark-mode
-c means "create." You're now on dark-mode. Any commits you make go here, not on main.
Older tutorials use git checkout -b dark-mode — same result, but git switch is clearer for beginners.
Work on the Branch
Edit your CSS as if you're building dark mode:
body {
background-color: #1a1a2e;
color: #eaeaea;
font-family: sans-serif;
max-width: 600px;
margin: 0 auto;
padding: 2rem;
}
h1 {
color: #7c3aed;
}
Commit on the branch:
git add styles.css
git commit -m "Add dark mode styles"
git log --oneline
Switch Back to Main
git switch main
Open styles.css — your dark mode changes are gone from the working files. They still exist on the dark-mode branch, safe and sound.
git switch dark-mode
Dark mode is back. Branches keep versions of your project separate.
Merge a Branch
Happy with dark mode? Bring it into main:
git switch main
git merge dark-mode
Git combines the commits from dark-mode into main. Your dark styles now live on main too.
git log --oneline
You'll see commits from both branches in main's history.
Delete a Branch
After merging, the branch has served its purpose:
git branch -d dark-mode
If you abandon an experiment without merging:
git branch -D experimental-feature
Capital -D forces deletion even if changes weren't merged — use when you're sure you don't want that work.
Branch Naming Tips
Use short, descriptive names:
fix-footer-linkadd-contact-pagedark-mode
Avoid spaces. Use hyphens or slashes: feature/dark-mode.
Typical Team Flow
- Create a branch for each feature or bug fix.
- Commit on that branch.
- Open a pull request on GitHub (next lesson) for review.
- Merge into
mainwhen approved. - Delete the branch.
You'll use branches every day once you're collaborating. For solo projects they're still useful — main stays clean while you experiment freely.