← Learning Hub
Beginner

Branches and Merging

A branch is a separate line of work. Build a new feature on its own branch while main stays working; when it's ready, merge it back.

A branch is a separate line of work. You can build a new feature on a branch without disturbing the main code, then merge it in when it's ready. Teams use branches so many people can work at once without stepping on each other.

Example
git switch -c dark-mode          # create a branch and move to it
# ... edit files ...
git add .
git commit -m "Add dark mode toggle"

git switch main                  # back to main
git merge dark-mode              # bring the feature in
# Updating 7c1e0b2..b41d2a8
# Fast-forward

git branch                       # list branches (* marks the current one)
git branch -d dark-mode          # delete it after merging

Fast-forward vs merge commit

  • Fast-forward: main hasn't changed since you branched, so Git just moves main forward.
  • Merge commit: both branches have new commits, so Git makes a commit that joins them.
Example
git log --oneline --graph
# *   e8f21c0 Merge branch 'dark-mode'
# |\
# | * b41d2a8 Add dark mode toggle
# * | 2c7d9e4 Fix footer link
# |/
# * 7c1e0b2 Add contact form
Older tutorials use git checkout -b name and git checkout main. They still work; git switch is the newer, clearer command.
Key points
  • git switch -c name creates and switches to a branch.
  • Work on features in branches, not on main.
  • git merge brings a branch's changes back.

📝 Test yourself

1. Which command creates a new branch and switches to it?
2. When is a merge a fast-forward?
3. Fill in the command that brings a branch into the current one:
git dark-mode