Skip to main content

Working with Branches

Branches are, without a doubt, the most powerful and important feature of using Git in a professional environment.

A branch represents an independent line of development. Think of it as an exact photocopy of your project at a given time, where you can experiment, delete things, or add new features without affecting the main version.

The Main Branch (main or master)

By default, every Git repository starts with a main branch that hosts the official code of the project. Historically it was called master, but the current standard is main.

Professional golden rule: NEVER write code directly in the main branch. This branch must always be kept stable, ready to be published or sent to production. All new developments are done in secondary branches.


See the existing branches: git branch

To know what branches your project has and which one you are currently working on:

git branch

You will see a list, and the branch you are currently on (the "active" one) will have an asterisk * next to it and will normally be green.

  feature-login
* main

Create a new branch

Suppose your boss asks you to add a "Dark Mode" to the page. To avoid breaking the page if something goes wrong, you will create an isolated branch from the current state of the code:

git branch feature-dark-mode

This creates the branch, but CAREFUL! You are still standing on the main branch. You have to "jump" to the new branch.

Switch branches (Checkout / Switch)

To physically move (so all your files change automatically) to another branch:

# The classic command (Still widely used)
git checkout feature-dark-mode

# The modern and recommended command (Introduced in 2019)
git switch feature-dark-mode

⭐️ Create and switch branch in one single step

In everyday real life, 99% of programmers combine creating and jumping branches in a single command to save time:

# Modern method (Recommended)
git switch -c feature-dark-mode

# Classic method
git checkout -b feature-dark-mode

The Workflow with Branches

  1. You are on main.
  2. You run git switch -c feature-login.
  3. You write the HTML and CSS code for the login.
  4. You run git add . and git commit -m "Add login screen".
  5. These changes only exist in the feature-login branch. main still doesn't know that the dark mode exists and remains in its previous version.

To merge both timelines and join the code, the Merge technique is needed.