6. Branching Basics

Branching is one of Git's absolute superpower features. While branching in old version control systems is a heavy, slow, and expensive process, Git branches are incredibly lightweight, fast, and created almost instantaneously.

What is a Branch?

A branch in Git is simply a **lightweight, movable pointer** to a specific commit. When you initialize a repository, the default branch is usually named main (or master). As you make commits on that branch, the pointer automatically moves forward to point to your latest commit.

Why use Branches?

Branches allow you to diverge from the main line of development to work on new features, fix bugs, or experiment without affecting the stable, production-ready codebase. Multiple developers can work on separate branches concurrently without stepping on each other's toes.

Core Branching Commands

1. Creating a Branch: git branch

To create a new branch at your current commit point without switching to it, type:

git branch feature/user-profile

2. Listing Branches

To see a list of all local branches in your repository, run:

git branch

This lists your local branches, highlighting your current branch with an asterisk (*) and in a different color. To list both local and remote-tracking branches, use:

git branch -a

3. Switching Branches: git switch or git checkout

To change your current working directory branch, use git switch (which was introduced in modern Git 2.23+ specifically for switching):

git switch feature/user-profile

Alternatively, you can use the older git checkout command to switch:

git checkout feature/user-profile

4. Create and Switch in One Command

A highly common shortcut is to create a new branch and immediately jump onto it in a single command:

# Modern Method
git switch -c feature/shopping-cart

# Older Method
git checkout -b feature/shopping-cart

5. Deleting a Branch

Once a feature branch is successfully merged into your main branch, it is best practice to clean up and delete it:

# Safely delete a branch (will fail if the branch has unmerged work)
git branch -d feature/shopping-cart

# Force delete a branch (even if it contains unmerged work)
git branch -D feature/shopping-cart
Rule: You cannot delete the branch that you are currently on. You must first switch to another branch (like main) before deleting it.

What is HEAD?

In Git, HEAD is a special pointer that tells Git which branch or commit you are currently standing on. Think of it as the "You Are Here" icon on a directory map. When you switch branches, Git automatically updates HEAD to point to the new active branch.