Refactoring your JavaScript Code —Part 1 — Create a Git Branch
You can learn a lot about yourself and how far you’ve come when you look back at an old project and think, ‘yikes, what was I thinking?’. Sure, the code works, but is it organized and efficient? Maybe you were rushed for time and just patched the code together, or maybe you were inexperienced and didn’t know how to write clean code. Maybe it wasn’t even your code, but you are working on it now. Whatever the reason, it’s always good practice to refactor.
Part 1 of this series will explore creating and merging a git branch on your repository. When I first started to learn git commands, branches and merging terrified me. It can become more complicated as multiple people are working on the same code, but for now, we’ll start with the basics.
A git branch is essentially a copy of your original code, in this case we’ll assume a copy of your master branch. It is independent from the master branch, so any changes, git commits, etc that are made on the new branch do not affect this master branch. It allows developers the freedom to explode their code safely and put it back together without the fear of losing a working version of their code (aka the master branch).
How to Create a New Git Branch
- Type
git branch
in your console to ensure you are in the master branch.
2. Type git checkout -b [name of new branch]
This command does three things:
- ‘checks out of’ the master branch
- creates a new branch. Note: the name of the new branch should not be within the [ ] brackets
- ‘checks in’ to the new branch. If you type
git branch
again, you should see the name of the new branch you created.
Now that you’ve created a new branch, you can freely edit your code without fear of breaking your working master branch. You can commit any changes to your repo like you normally would with git add
, git commit
, and git push
, except now all the changes will be pushed to your newly created branch.
When you go to your git repo, you’ll notice a few things. From your master branch, you won’t notice any of the new commits, but you’ll have a notification that your new branch was recently updated.
When you change to your new branch, you’ll notice how many git commits you’ve done. In my case I’ve made 4 commits to the new branch.
You can edit, commit, and push your changes as needed, but before you do this, double check you’re in the new branch by running a quick git branch
.
We’ll learn how to merge your branches in Part 2 of this refactoring series. If you have any comments, suggestions, or just want to say hi, feel free to comment below!