In this lesson, you will learn how to create a new branch to keep your experimental work separate from your stable, primary codebase.
Why Isolate Your Work?
Up until now, you have likely been committing changes directly to your main branch. While this is fine for small solo projects, it becomes risky as your project grows. If you start working on a new feature—like adding a login screen—and realize halfway through that it breaks other parts of your app, your main branch is now in a broken state.
By using branches, you create a parallel version of your project. You can build, test, and break things in your new branch without ever affecting the files in main.
Creating Your First Feature Branch
To start, you need to create a new branch. Using the git branch command creates a "pointer" to your current position in the history, allowing you to branch off and go your own way.
-
Create the branch:
git branch feature-loginThis creates a new branch named
feature-login. -
Switch to the branch:
git checkout feature-loginNow that you have switched to this branch, any commits you make will be recorded here instead of on
main. You can verify you are in the right place by runninggit branch, which highlights your current branch with an asterisk (*).
Making Progress Safely
Once you are on your feature-login branch, you can add files, stage them, and commit them as usual. If you decide you want to check your main branch, you can simply run git checkout main. Git will automatically swap the files in your working directory back to how they looked before you started your feature work. When you return to git checkout feature-login, your feature progress reappears exactly where you left it.
This workflow ensures your main branch remains a "clean" history of working, tested code, while your feature branches handle the "messy" reality of active development.
Key Takeaway: Using branches allows you to experiment freely by creating a safe, isolated environment that keeps your primary project files stable until your new features are ready to be integrated.