Skip to content
Programming contents

Lesson 2.5.4: Branches

A branch is a separate line of work: you try something without touching what already works.

The idea

Until now, each commit came after the previous one, in a single line: the main branch.

A branch is another line of commits that starts from there. You try whatever you like on it, and main stays untouched. If it works out, you join the two; if not, you throw it away.

Creating a branch and switching to it

Terminal
git switch -c goodbye
Terminal
Switched to a new branch 'goodbye'

-c creates it. git branch lists the branches, with * next to the current one:

Terminal
git branch
Terminal
* goodbye
  main

Working on it

Add this at the end of hello.js:

JavaScript
console.log("Goodbye");

And save it in a commit, as always:

Terminal
git add hello.js
git commit -m "feat(greeting): add the goodbye"

Back to main

Terminal
git switch main

Look at hello.js: the goodbye isn't there. That line only exists on the other branch.

Joining the branches

From main, bring in what's on the other branch:

Terminal
git merge goodbye
Terminal
Updating 7b1e0d4..9c2f5a8
Fast-forward
 hello.js | 1 +
 1 file changed, 1 insertion(+)

Now main has the goodbye. The branch isn't needed any more:

Terminal
git branch -d goodbye

If both change the same thing

If both branches changed the same line, Git doesn't know which to keep: that's a conflict. It marks the file with both versions, you keep the right one, and you add and commit. VS Code shows it with buttons to choose.

Try it

Exercise

Create a branch table-of-5, change table.js to the 5 times table, commit with a message from 2.5.2 and join the branch into main.

Show the solution
Terminal
git switch -c table-of-5
git add table.js
git commit -m "feat(table): switch to the 5 times table"
git switch main
git merge table-of-5
git branch -d table-of-5

Between the first line and the second, change the 3 to a 5 in table.js and save.

Summary

  • A branch is a separate line of work; the main one is main.
  • git switch -c name creates a branch and switches to it; git switch main goes back.
  • git merge name brings the other branch's work into the current one.
  • If both changed the same line, there's a conflict and you choose.