55 Mins

4. Branching — The Killer Feature

Core Concept

Branching is the feature that makes Git indispensable. A branch is an independent line of development — a parallel universe of your codebase. You can create a branch to build a new feature, break everything, learn from it, and then delete the branch. The main codebase is untouched the entire time.

Creating and Switching Branches

See all branches (current branch is marked with *):

Bash
git branch

Create a new branch:

Bash
git branch feature/user-authentication

Switch to the new branch:

Bash
git checkout feature/user-authentication

Create AND switch in one command (preferred modern way):

Bash
git checkout -b feature/user-authentication

Even newer syntax (Git 2.23+):

Bash
git switch -c feature/user-authentication

Check which branch you're on (Output: On branch feature/user-authentication):

Bash
git status

Merging a Branch

When a feature is complete, you merge the branch back into main. Git combines the histories of both branches. Switch back to the main branch first:

Bash
git checkout main

Merge the feature branch into main. If the merge was clean (no conflicts), you will see a fast-forward update message:

Bash
git merge feature/user-authentication

Delete the branch (it's been merged, you don't need it anymore):

Bash
git branch -d feature/user-authentication

Merge Conflicts — When Two Branches Edit the Same Line

A merge conflict occurs when two branches have modified the same line of the same file differently. Git cannot guess which change to keep — it asks you to decide. When a conflict occurs, git merge will output an automatic merge failed warning.

Open the conflicted file. Git marks conflicts like this:

Bash
<<<<<<< HEAD
  const greeting = "Hello";
=======
  const greeting = "Hi there";
>>>>>>> feature/user-authentication

Your job:

  1. Delete the conflict markers (<<<, ===, >>>)
  2. Keep the version you want (or write a new combination)
  3. Save the file

Then stage and commit the resolution:

Bash
git add app.js
git commit -m "Merge feature/user-authentication: resolve greeting conflict"
Use a merge tool to visualise conflicts side-by-side. git mergetool opens your configured diff viewer. VS Code has an excellent built-in merge editor — install the GitLens extension for even more power.

Branch Naming Conventions

  • feature/description — New features: feature/user-authentication, feature/dark-mode
  • fix/description — Bug fixes: fix/login-timeout-error
  • hotfix/description — Urgent production fixes: hotfix/payment-api-null-crash
  • chore/description — Maintenance, dependency updates: chore/update-dependencies
  • docs/description — Documentation only: docs/api-reference-update

Knowledge Check

Ready to test your understanding of 4. Branching — The Killer Feature?

Back