4. Branching — The Killer Feature
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 *):
git branch
Create a new branch:
git branch feature/user-authentication
Switch to the new branch:
git checkout feature/user-authentication
Create AND switch in one command (preferred modern way):
git checkout -b feature/user-authentication
Even newer syntax (Git 2.23+):
git switch -c feature/user-authentication
Check which branch you're on (Output: On branch feature/user-authentication):
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:
git checkout main
Merge the feature branch into main. If the merge was clean (no conflicts), you will see a fast-forward update message:
git merge feature/user-authentication
Delete the branch (it's been merged, you don't need it anymore):
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:
<<<<<<< HEAD const greeting = "Hello"; ======= const greeting = "Hi there"; >>>>>>> feature/user-authentication
Your job:
- Delete the conflict markers (
<<<,===,>>>) - Keep the version you want (or write a new combination)
- Save the file
Then stage and commit the resolution:
git add app.js git commit -m "Merge feature/user-authentication: resolve greeting conflict"
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-modefix/description— Bug fixes:fix/login-timeout-errorhotfix/description— Urgent production fixes:hotfix/payment-api-null-crashchore/description— Maintenance, dependency updates:chore/update-dependenciesdocs/description— Documentation only:docs/api-reference-update
Knowledge Check
Ready to test your understanding of 4. Branching — The Killer Feature?