Visual Studio Code

Code Snippets

Visual Studio Code

Check out a free preview of the full Visual Studio Code course

The "Code Snippets" Lesson is part of the full, Visual Studio Code course featured in this preview video. Here's what you'd learn in this lesson:

Mike introduces code snippets, which are templates for entering repeating code patterns.


Transcript from the "Code Snippets" Lesson

>> Mike North: So I told you we'd deal with code snippets here. These are extensions to Emmet. Emmet is sort of the core of the code snippet functionality that is built into VS Code. And we've got a couple things going on here. First off, you see that we've got a name here called For Loop.

That is sort of the name of this snippet. And we're gonna start typing this and then hit Tab once it recognizes we're working with the For Loop. And we will get this body. Right, sorry, we' re gonna type for. This will be shown in the tool tip as sort of a description of what we're working with.

And then the body will be pasted into our code. You'll note that we've got the \t here. So this is just text. It is your responsibility to make sure that this turns into valid code. And you'll note that we have a couple things that look like this. We've got 1:index.

So basically the thing before the colon, well, these are parameters first of all. Remember with Emmet where we could tab between different things, and we'd sort of fill in all of the blanks? This is what defines a blank to fill in. So what this is saying is it's the first parameter, and the default we're gonna fall back on to is index, or initially it's gonna be index.

But the number 1 means that that index, and this index, and this index here, those are all gonna be kind of linked together as the same variable. So as I try to rename something, it should end up renaming all of them. Let's see how that works. So this is our for loop.

It's a user snippet. I have it in place already to demo to you. Okay, so now when I, this is the first parameter, and because those all were 1:index, now when I turn this to i, all of them get turned into i. It's really three or four references to the same variable, and so it's regarded as one placeholder.

I'm gonna hit the Tab key. Now I'm on this array, and so I could say list. And then the Tab key once more, oops, I messed that up, didn't I?
>> Mike North: i, Tab, list.
>> Mike North: Tab, thisItem, something like that. And now we've defined our for loop. List doesn't exist, that's what it's telling us.

So this is sort of Emmet working for you in JavaScript. Where you can just have an abbreviation, hit Tab, expand it out, fill in your placeholders really, really nice.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now