Branching

A branch is an independent line of work. Branching lets you try something new — a feature, a fix, an experiment — without touching the working version of your project until you're ready.

Why branch instead of just editing

Without branches, every commit lands on the same single timeline. That's fine solo and for tiny changes, but it breaks down fast once you're mid-way through a risky change and suddenly need to fix an urgent bug on the working version — your half-finished feature is sitting right there mixed in. Branches solve this by letting the "main" line of history stay stable while you do your work somewhere else, then bring it back in only when it's ready. Every commit belongs to a branch, and you can switch between branches at will.

git branch

List existing branches, and see which one you're currently on (marked with *):

$ terminal
git branch
Terminal output
* main

Create a new branch without switching to it:

$ terminal
git branch contact-form

Switching branches

To actually move your working files onto a different branch, use git switch (the modern, clearer command) or the older git checkout:

$ terminal
git switch contact-form
# or, the older equivalent:
git checkout contact-form

Create and switch to a new branch in one step by adding -c (or -b with checkout):

$ terminal
git switch -c contact-form
# or:
git checkout -b contact-form

From here, any commits you make happen on contact-form, completely separate from main. You can switch back to main at any time with git switch main, and your files will instantly reflect main's state — the contact-form work isn't lost, it's just parked on its own branch waiting for you to return to it.

A typical workflow

  1. Start on main, make sure it's up to date.
  2. Create a branch for the thing you're about to do: git switch -c fix-nav-bug.
  3. Make commits on that branch as you work.
  4. When it's done and tested, merge it back into main (next lesson).
Note: branch names are cheap and disposable — creating one costs nothing, so it's normal to make a new branch for even a small, five-minute fix rather than committing directly to main.