In the previous chapter, we learned how to edit files, stage changes with git add, and create commits with git commit. The next major Git concept is the branch.
A branch is an independent line of development. Suppose your project is currently working well, but you want to add a new login feature. If you make all of your changes directly on the main version of the project, unfinished or broken code could affect the stable code.
A common approach is to create a separate branch for the new feature, complete the work there, and merge it back into the main branch when it is ready.
A visual map makes the relationship clearer:
Here, main is the main branch of the project, while login-feature is a separate branch created for login development.
Suppose main contains A → B → C. After creating a branch from commit C, login-feature adds D and E, while main remains at C.
Commits D and E belong to the login-feature branch, so they do not immediately change main. Once the feature is complete, those changes can be merged back into the main branch.
Why Use Branches for New Work?
Branches keep different pieces of work separated. A team might maintain main, feature/login, feature/payment, and fix/profile-error at the same time.
One developer can work on login, another can work on payments, and someone else can fix a profile bug. Each person can work independently without constantly changing the main branch.
Branches are also useful when you are working alone. You might want to experiment with an idea, build a feature that is not finished yet, or fix a bug without disturbing your current stable version.
KNOWLEDGE QUIZ
What Is main?
Most new GitHub repositories use:
mainas the default branch name.
The main branch usually represents the primary line of development. Many teams try to keep it reasonably stable, so new features are often developed on separate branches first.
Older repositories may still use:
masterinstead of main. In this tutorial, we will use main.
A Branch Is Not a Copy of the Whole Project
A branch does not mean Git makes a complete duplicate of your project folder. Internally, branches are lightweight references to different points in Git history, which is why creating them is very fast.
You do not normally need separate folders like:
project-main
project-login
project-paymentYou usually work inside the same project folder and switch between branches using Git.
Practice
A stable website needs a login feature and a payment-page fix at the same time. Explain why doing both directly on main is risky, and propose a clear branch name for each task.