Falytom logoFALYTOM
Games
ToolsUI ComponentsServicesProductsAbout
menu
  1. Home
  2. /Web Development
  3. /Github
  4. /Working With Branches
Your Progress0%
0 of 20 completed

Git & Github Topics

Getting Started

  • What is Git?
  • What is GitHub?
  • Installing & Configuring Git
  • Your First Git Repository

Core Git Concepts

  • Understanding Commits & History
  • Working with Branches
  • Merging Branches
  • The Staging Area
  • Undoing Changes

Working with GitHub

  • Connecting to GitHub
  • Pushing & Pulling Code
  • Cloning Repositories
  • GitHub README & Documentation

Collaboration Workflows

  • Forking & Pull Requests
  • Code Review Basics
  • Handling Merge Conflicts
  • Issues & Project Management

Best Practices & Workflows

  • Git Workflow Best Practices
  • Working with .gitignore
  • Common Git Problems & Solutions

Working with Branches

Create isolated workspaces for features and experiments

Branches are one of Git's most powerful features, enabling you to work on multiple features simultaneously, experiment without risk, and organize your development workflow. Think of branches as parallel universes for your project—each branch is an independent line of development where you can make changes without affecting other branches. In this lesson, you'll learn what branches really are, how to create and switch between them, and why they're essential for modern software development.

What Are Branches?

A branch in Git is a lightweight, movable pointer to a specific commit. Despite the name, it's not a copy of your files—it's simply a reference that points to a commit in your history.

The Mental Model

Think of your Git history as a timeline of commits:

TEXT
A --- B --- C --- D --- E  (main branch)

The branch name main is just a label pointing to commit E (the most recent commit). When you create a new branch, you're just creating a new label:

TEXT
A --- B --- C --- D --- E  (main)
                        \
                         E  (feature)

Now you have two branches, both pointing to the same commit E. When you make a new commit on the feature branch:

TEXT
A --- B --- C --- D --- E  (main)
                        \
                         E --- F  (feature)

The feature branch moves forward to point to the new commit F, while main stays where it was.

Key Insight: Branches are incredibly lightweight in Git. Creating a branch takes less than a second and uses virtually no disk space because you're not copying files—you're just creating a 41-byte file containing a commit hash!

Why Branches Matter

Branches enable several crucial workflows:

  • Isolated Development: Work on a new feature without breaking the main codebase
  • Experimentation: Try risky changes in a branch; delete the branch if they don't work out
  • Parallel Work: Multiple people (or you) can work on different features simultaneously
  • Bug Fixes: Create a quick branch to fix a bug while keeping feature work separate
  • Code Review: Branches make it easy to review changes before merging them
  • Release Management: Maintain different versions of your software

🌳 Why 'Branches'?

The name "branch" comes from the tree analogy. Your main development line is the trunk, and branches split off to explore different directions. Unlike real tree branches though, Git branches can merge back together!

The Default Branch

When you initialize a Git repository with git init, Git automatically creates a default branch. Historically, this was called master, but modern Git versions use main.

Main vs Master: Many teams and platforms (including GitHub) now use main as the default branch name instead of master. They both serve the same purpose—it's just a naming convention. When you see either term in this tutorial, they're interchangeable.

The default branch typically represents your production-ready code or the main line of development. All other branches usually split off from and eventually merge back into this branch.

Viewing Branches

Let's start by looking at the branches in your repository.

List All Branches

BASH
git branch

This shows all local branches, with an asterisk marking your current branch:

TEXT
* main
  feature/login
  bugfix/header

The * indicates you're currently on the main branch.

Verbose Branch Information

See each branch with its last commit:

BASH
git branch -v
TEXT
* main           a1b2c3d Fix navigation bug
  feature/login  f4e5d6c Add login form validation
  bugfix/header  c7d8e9f Fix header overflow on mobile

All Branches (Including Remote)

We'll cover remote branches later, but you can see them with:

BASH
git branch -a

Creating Branches

Create a New Branch

To create a new branch, use:

BASH
git branch feature/user-profile

This creates a new branch called feature/user-profile pointing to your current commit. However, you're still on your original branch!

📝 Branch Naming Conventions

Common branch naming patterns:

  • feature/description - For new features
  • bugfix/description - For bug fixes
  • hotfix/description - For urgent production fixes
  • experiment/description - For experiments
  • refactor/description - For code refactoring

Use lowercase with hyphens or slashes. Be descriptive but concise!

Check Your Branches

BASH
git branch
TEXT
  feature/user-profile
* main

The new branch exists, but you're still on main (notice the *).

Switching Between Branches

To actually work on a branch, you need to switch to it. Git provides two commands for this:

Using git switch (Modern, Recommended)

BASH
git switch feature/user-profile
TEXT
Switched to branch 'feature/user-profile'

Now when you check branches:

BASH
git branch
TEXT
* feature/user-profile
  main

The * moved! You're now on the feature/user-profile branch.

Using git checkout (Traditional)

The older way to switch branches (still widely used):

BASH
git checkout main

git switch vs git checkout:

git switch was introduced in Git 2.23 (2019) to make branch operations clearer. git checkout does many things (switch branches, restore files, create new branches), which can be confusing.

Modern approach:

  • git switch - For switching branches
  • git restore - For restoring files

Both work, but git switch is more explicit and recommended for new learners!

Create and Switch in One Command

Instead of creating a branch and then switching to it, do both at once:

BASH
# Modern way
git switch -c feature/dark-mode

# Traditional way
git checkout -b feature/dark-mode

The -c flag (create) or -b flag creates the branch and switches to it immediately.

⚡ Productivity Tip

Most developers use the create-and-switch pattern 90% of the time. You rarely create a branch without immediately switching to it!

Working on a Branch

Once you're on a branch, everything works the same as before. Let's practice:

  1. Create and switch to a new branch:
BASH
git switch -c feature/contact-form
  1. Make some changes:

Create a new file contact.html:

contact.html
<!DOCTYPE html>
<html>
<head>
    <title>Contact Us</title>
</head>
<body>
    <h1>Contact Form</h1>
    <form>
        <input type="text" placeholder="Your name" required>
        <input type="email" placeholder="Your email" required>
        <textarea placeholder="Your message"></textarea>
        <button type="submit">Send</button>
    </form>
</body>
</html>
  1. Stage and commit your changes:
BASH
git add contact.html
git commit -m "Add contact form page"
  1. Check your commit history:
BASH
git log --oneline
TEXT
f4e5d6c (HEAD -> feature/contact-form) Add contact form page
a1b2c3d (main) Fix navigation bug
c7d8e9f Update homepage design

Notice that HEAD points to feature/contact-form, and this branch is one commit ahead of main.

  1. Switch back to main:
BASH
git switch main
  1. Check if the file exists:
BASH
ls contact.html

The file doesn't exist on main! When you switched branches, Git updated your working directory to match the main branch, where contact.html was never created.

  1. Switch back to your feature branch:
BASH
git switch feature/contact-form
ls contact.html

The file is back! Git switched your working directory back to the feature branch state.

This is the magic of branches! Each branch maintains its own version of the project. You can switch between them instantly, and Git handles updating all your files.

Interactive Branch Visualization

Try this interactive tool to see how branches work:

Experiment with Git Branches

Create branches, make commits, and see how they relate

main
Initial commit
10:00 AM
Add features
11:30 AM

Commit Log

Add features

main • 11:30 AM

Initial commit

main • 10:00 AM

Branch Management

Renaming Branches

Rename the branch you're currently on:

BASH
git branch -m new-branch-name

Rename a different branch:

BASH
git branch -m old-name new-name

Deleting Branches

Once you're done with a branch (usually after merging it), you can delete it:

BASH
# Safe delete (only if merged)
git branch -d branch-name

# Force delete (even if not merged)
git branch -D branch-name

Be Careful! You can't delete the branch you're currently on. Switch to a different branch first.

BASH
git switch main
git branch -d feature/contact-form

🗑️ Don't Fear Deletion

Deleting a branch only removes the branch pointer—the commits themselves remain in Git's history (at least for a while). If you delete a branch by accident, you can usually recover it!

Viewing Branch Relationships

See which branches are merged into your current branch:

BASH
# Branches merged into current branch
git branch --merged

# Branches not yet merged
git branch --no-merged

This helps you identify which branches can be safely deleted.

Important Notes About Switching Branches

Uncommitted Changes

Git won't let you switch branches if you have uncommitted changes that would be overwritten:

BASH
# Make some changes
echo "new content" > test.txt

# Try to switch branches
git switch main
TEXT
error: Your local changes to the following files would be overwritten by checkout:
        test.txt
Please commit your changes or stash them before you switch branches.
Aborting

You have three options:

  1. Commit your changes:
BASH
git add test.txt
git commit -m "Update test file"
git switch main
  1. Discard your changes:
BASH
git restore test.txt
git switch main
  1. Stash your changes (we'll learn this later):
BASH
git stash
git switch main
# Later: git stash pop

Clean Working Directory

Before switching branches, it's good practice to have a clean working directory:

BASH
# Check status
git status

# Should see:
# nothing to commit, working tree clean

Common Branch Workflows

Feature Branch Workflow

The most common workflow: create a branch for each feature or task.

BASH
# Start working on a new feature
git switch -c feature/user-profile

# Make changes, commit often
git add .
git commit -m "Add profile page structure"

# More work...
git add .
git commit -m "Add profile edit functionality"

# When done, switch back to main
git switch main

# Merge your feature (next lesson!)
git merge feature/user-profile

# Delete the feature branch
git branch -d feature/user-profile

Bug Fix Workflow

Quickly fix a bug without disturbing your feature work:

BASH
# Currently working on a feature
git switch feature/dashboard

# Bug report comes in!
# Switch to main and create bug fix branch
git switch main
git switch -c bugfix/login-error

# Fix the bug
git add .
git commit -m "Fix login redirect error"

# Merge fix to main
git switch main
git merge bugfix/login-error

# Delete bug fix branch
git branch -d bugfix/login-error

# Go back to your feature work
git switch feature/dashboard

Experiment Workflow

Try something risky without affecting your main work:

BASH
# Create experimental branch
git switch -c experiment/new-algorithm

# Try the new approach
# ... make changes ...
git commit -am "Try new sorting algorithm"

# Doesn't work well?
# Just delete the branch!
git switch main
git branch -D experiment/new-algorithm  # Force delete

# Or if it worked:
git switch main
git merge experiment/new-algorithm

Branch Best Practices

1. Use Descriptive Names

Good:

  • feature/user-authentication
  • bugfix/header-overflow
  • refactor/database-queries

Bad:

  • branch1
  • temp
  • test
  • asdf

2. Keep Branches Short-Lived

Branches that live for weeks or months become hard to merge. Aim to complete, merge, and delete branches within days.

3. Commit Often on Branches

Make small, frequent commits on your feature branches. You can always clean up the history later if needed.

4. Keep Main Branch Stable

The main branch should always be in a working state. Only merge code that's tested and ready.

5. Delete Merged Branches

Once a branch is merged, delete it. This keeps your branch list clean and prevents confusion.

6. Pull Before Creating New Branches

When working with others (we'll learn this soon), always update your main branch before creating a new feature branch:

BASH
git switch main
git pull
git switch -c feature/new-feature

Understanding HEAD with Branches

Remember HEAD from the previous lesson? When working with branches, HEAD typically points to the current branch, which points to a commit:

TEXT
HEAD -> feature/login -> commit abc123

You can see where HEAD points:

BASH
# See what HEAD points to
cat .git/HEAD

# Output:
# ref: refs/heads/feature/login

When you switch branches, HEAD moves:

BASH
git switch main
cat .git/HEAD

# Output:
# ref: refs/heads/main

Practice Branch Commands

Try these commands to practice working with branches:

Practice Git Branches

Experiment with creating and switching branches

$

Try these examples:

Common Branch Issues

Issue: Can't Switch Branches

Error: "Please commit your changes or stash them before you switch branches"

Solution: You have uncommitted changes. Either commit them, discard them, or stash them:

BASH
# Option 1: Commit
git add .
git commit -m "Work in progress"

# Option 2: Discard
git restore .

# Option 3: Stash (temporary storage)
git stash

Issue: Branch Doesn't Exist

Error: "pathspec 'feature/login' did not match any file(s) known to git"

Solution: The branch doesn't exist. Check available branches:

BASH
git branch -a

Issue: Deleted Branch by Accident

Problem: You accidentally deleted a branch

Solution: If the branch was merged, the commits still exist. If not merged, check the reflog:

BASH
# See recent HEAD movements
git reflog

# Find the commit where your branch was
# Create a new branch at that commit
git branch feature/recovered abc123

Command Reference

Here's a quick reference of all branch commands:

BASH
# Viewing Branches
git branch                    # List local branches
git branch -v                 # List with last commit
git branch -a                 # List all (including remote)
git branch --merged           # List merged branches
git branch --no-merged        # List unmerged branches

# Creating Branches
git branch branch-name        # Create new branch
git switch -c branch-name     # Create and switch (modern)
git checkout -b branch-name   # Create and switch (traditional)

# Switching Branches
git switch branch-name        # Switch branches (modern)
git checkout branch-name      # Switch branches (traditional)
git switch -                  # Switch to previous branch

# Managing Branches
git branch -m new-name        # Rename current branch
git branch -m old new         # Rename specific branch
git branch -d branch-name     # Delete merged branch
git branch -D branch-name     # Force delete branch

# Branch Information
git show-branch              # Show branch relationships
git log --oneline --graph    # Visual commit graph

Key Takeaways

  • Branches are lightweight pointers to commits, not copies of files
  • Use git branch to create branches and list them
  • Use git switch or git checkout to switch branches
  • Each branch maintains its own version of your project
  • Branches enable parallel development and experimentation
  • Common patterns include feature branches, bug fix branches, and experiment branches
  • Always commit or stash changes before switching branches
  • Delete branches after merging to keep your repository clean
  • HEAD points to your current branch, which points to a commit
  • Branch operations in Git are extremely fast and lightweight

What's Next?

Excellent work! You now understand how to create and work with branches—one of Git's most powerful features. You can create isolated workspaces for different features, switch between them instantly, and organize your development workflow effectively.

But branches are only half the story. In the next lesson, we'll learn about merging branches. You'll discover how to combine the work from different branches, understand merge strategies, and handle the process of bringing feature branches back into your main codebase. This is where branches really prove their power!

🎯 Practice Assignment

Before the next lesson, practice working with branches:

  1. Create at least 3 different feature branches
  2. Make 2-3 commits on each branch
  3. Practice switching between branches and observing how files change
  4. Use git log --oneline --graph --all to visualize your branches
  5. Try renaming a branch
  6. Experiment with the interactive branch visualizer above

The more comfortable you are with branches, the easier merging will be!

Test Your Understanding of Git Branches

Question 1 of 4

What is a branch in Git?

Current Score0 / 0

Know someone who'd find this guide helpful? Please share!

Previous
Understanding Commits & History
Next
Merging Branches

Never Miss a New Git & GitHub Tutorial

Join 2,000+ developers learning Git & GitHub step-by-step. Get new tutorials, tips, and exclusive resources delivered to your inbox - completely FREE.

You might also like

UI Components

Ready-made components for your projects

Developer Tools

Boost productivity with handy generators

HTML Game

Learn HTML concepts through interactive gameplay

Join Our Web Development Training Program

Master frontend & backend development with hands-on projects.

Git & Github Tutorials

0 of 20 completed

Your Progress0%

Topics

Getting Started

  • What is Git?
  • What is GitHub?
  • Installing & Configuring Git
  • Your First Git Repository

Core Git Concepts

  • Understanding Commits & History
  • Working with Branches
  • Merging Branches
  • The Staging Area
  • Undoing Changes

Working with GitHub

  • Connecting to GitHub
  • Pushing & Pulling Code
  • Cloning Repositories
  • GitHub README & Documentation

Collaboration Workflows

  • Forking & Pull Requests
  • Code Review Basics
  • Handling Merge Conflicts
  • Issues & Project Management

Best Practices & Workflows

  • Git Workflow Best Practices
  • Working with .gitignore
  • Common Git Problems & Solutions
Falytom logoFALYTOM

Learn technologies like HTML, CSS, JavaScript, React, NodeJS and more through interactive games, tutorials, components and free tools. Transform your businesses with AI chatbots, SEO-optimized websites, and professional development services.

© 2025 Tomilola Group
  • Facebook logo
  • Twitter logo
  • Instagram logo
  • LinkedIn logo
  • GitHub logo
  • YouTube logo