Code Snippets, JavaScript

Stephen Galvan
7 min readAug 16, 2020
Photo by Erwan Hesry on Unsplash

What is a code snippet?

A code snippet, put simply, is a snippet of code. It is any collection of previously written code that a developer would like to call on again to use for future reference. This may sound too good to be true, or you may already be using snippets. If you are new to snippets, this is a guide on how to use them. A snippet of code, allows you to use previously written code again and again using custom made shortcuts or prefixes. In this blog I will show you how this works. My goal is that by the end of this blog you are equipped with a tool that makes your work flow more efficient. To follow along you may want to install VS code if you haven’t already, and the following extensions as well:

Custom Snippets,
JavaScript (ES6) code snippets.

Otherwise, feel free to come back to this whenever, or pause here to look up info on your specific code editor for how to use code snippets. Or you can continue reading along. You should be able to walk away with an understanding of how to apply this information to suit your coding journey.

To get started, let’s open up our code editor.

Here is an example of some JavaScript code snippets in use:

In the example above, we are typing out what are called prefixes for two different snippets. The first prefix clg , prints the snippet console.log() provided by the JavaScript6 code Snippet Extension. The second snippet is a fetch request snippet I created using Custom Snippets and used the prefix fetch. I’ll say more about prefixes in a bit. By typing out just a few characters or a keyword, we can call on an entire saved snippet of code. Some questions you may have or may not even know you have… Where are we storing these snippets? What else can we do with snippets other than saving them and calling them for later?

Let’s get started

Some questions will be answered as we go along. To begin, if you are on a mac hit Command + Shift + “p” otherwise, hit Ctrl + Shift + "p" to open up the search bar menu in VS code and then type in “Configure User Snippets”. In the image below, because I’ve used snippets before, I will be asked to select from a few languages that I have used most recently to create snippets for. Feel free to use whatever language you prefer; it works the same way. For this blog I will create a snippet for JavaScript.

Regardless of the language you use, the process of creating a snippet should work the same.

Once choosing the language, a .json file will open - this file will function as a library for your code snippets for the specific language you chose.

Whatever language you choose to create snippets for, they will all open up with the same template of commented code. These are instructions for using and creating code snippets. Feel free to read them and refer back to them as you continue creating snippets. I recommend NOT deleting any of this code for now.

You will also notice that some of the brackets are not commented out. The only brackets that really matter here are the very first brackets that surround the commented code. They are colored yellow in the image above. I will refer to them as the Snippet Container. These brackets will function as a container for all the snippets we want to save.

The four main components to snippets

*And an optional 5th (when appropriate)

  • The Title of your snippet
  • The Prefix, or keyword used to call on your snippet
  • The Body of the snippet
  • and the Description
  • *Possible Variables * are found in the body.

I want to call your attention to the bracket immediately following the Title. This bracket tells us that everything following the Title is an Object. When we create snippets, we are effectively, creating an object with its own key value pairs. The keys are “prefix”, “body”, and “description”. Do not change these naming conventions.

The Prefix can be named anything. The shorter the better, but it also has to make sense to you. I named my fetch snippet “fetch” because it’s small enough to me, and the name makes sense.

The Body is the section of our snippet where our actual lines of code will go. The Body takes in the code you want to use as an array of strings. To start the body, use the square brackets [ ] and insert your code inside, line by line. Make sure your code is written out as strings and that each line of code ends with a comma, unless it is the very last line of code.

The description of the snippet is sort of like the definition of your code snippet. It’s there to function as a note for you when you call on it for future use.

To create snippets, here is an example format below:

The surrounding bracket represents the snippets container. If you did not delete the commented code in the .json file, then you just need to insert the snippet inside of the brackets that represent the snippet container:

{ //snippet container    "DOM Content Loaded":{
"prefix": "dcl",
"body": [
"document.addEventListener('DOMContentLoaded', () => {",
" ",
"})"
],
"description": "DOMContentLoaded is an asynchronous event that fires after an HTML file has been completely loaded"
},
//below here you can add a new snippet like so:
"New Snippet Title": {
"prefix": "sample",
"body": [
"body content"
]
"description": "This is like a definition"
}
} //snippet container

Creating a new Snippet

I said I would go over Possible Variables, and I will do that now. Let’s create a JavaScript Snippet for an Array Method called Reduce. You can read more about reduce in my last blog: JavaScript, Tricks with Reduce

Reduce is made up of several components.
(1) Let’s set an array = [10, 20]
array.reduce((2) callback Function((3) Accumulator, (4) Current Element) => {return Accumulator + CurrentElement}, (5) Initial Value)

const reduceArray = array.reduce((sum, currentElement) => {
return sum + currentElement;
}, 0);
//=> returns 30

We will be creating a snippet using the code above.

  • To start make sure that your snippet gets created inside of the snippet container.
  • Next let’s name our snippet “Reduce” and give it the prefix “reduce” and set up our body as an empty array.
  • Copy and paste the sample reduce code that we just created in this article above inside of the body. Next let’s refactor the code in our body…
  • Stringify each line of code, and end each line with a comma (,)
  • We are almost Done. Next let’s add some Possible Variables. Possible variables are marked by the Dollar sign “$” character and a number starting at one “1”. You can also set placeholder values for possible variables, and once a placeholder value has been set, by simply referring to that assigned number later on, the same placeholder will appear when called in the text editor.
  • Let’s refactor the code in our body to look like this:
"const $1 = ${2:array}.reduce((${3:accumulator}, ${4:currentValue}) => {",
"return $3 + $4;",
"}, ${5:0}"

Finally let’s add our finishing touches. Close off our body array with a comma and in the following line insert a description. And you should have a finished snippet that looks something like this:

Reduce method as a Snippet in JSON format

Now, let’s test this out in our code editor:

Using the reduce code snippet inside of text Editor

To conclude, create snippets. Snippets are a handy way to shrink down the amount of work you do in future projects. Hopefully this blog offered some new insights into your coding journey. Thank you for reading. If you have any questions, comments or feedback, or would like for me to cover any topics in the future, I am always happy to connect.

--

--

Stephen Galvan

A Software Engineer with a background in Education Technology and Dance. Recent grad form FlatIron Bootcamp, and passion for the arts and working with databases