How to Run JavaScript in Visual Studio Code and Program Like a Pro

Hi there! As a fellow developer, you likely already know – JavaScript has grown to become the most popular programming language. And Visual Studio Code rose up to be the code editor of choice for millions of devs.

In this comprehensive 4,000+ words guide, you‘ll learn:

  • Why VS Code and JS are a match made in heaven
  • How to set up a complete JS dev environment
  • Writing, running, testing and debugging JS programs
  • Following coding best practices for clean, maintainable code
  • Pushing code to GitHub, tracking changes with Git
  • Leveling up skills through expert JS resources

So buckle up and let‘s get started! By the end, you‘ll be able to build JS apps faster and troubleshoot bugs more easily.

Overview – Why JS and VS Code are Better Together

Before jumping into code, let me convince you why VS Code is the perfect code editor for JavaScript.

73% of developers use VS Code today – and that number keeps rising! The StackOverflow Developer Survey 2022 found VS Code is the #1 editor among devs worldwide.

And an equal majority love writing JS. 63% identified JavaScript as their most used programming language (as per the same survey).

What makes this combo so popular? Here are a few reasons:

1. Exceptional JS support

VS Code provides excellent support and tooling for JavaScript – right out of the box. It understands JS syntax, provides intelligent auto-completions, detects errors and poor quality code on the fly.

2. Debugging and testing made easy

You can quickly set breakpoints, analyze variable values and step through JS execution to fix bugs. Run unit tests and get coverage reports without any setup.

3. Thousands of extensions

Install extensions to add new features like linting, Git tools, themes, code formatting, etc. You can also customize VS Code for specific JS frameworks like React or Angular.

4. Streamlined workflow

The intuitive UI, split editing, Terminal access and GitHub integration leads to a highly productive environment for JS developers.

Convinced about the power-combo? Let‘s look at how we can harness it.

Setting Up Node.js and VS Code

For running JavaScript, you need:

  1. Node.js runtime
  2. VS Code editor

Here is how to install both:

Step 1: Install Node.js

Node.js lets you run JavaScript on servers and build server-side applications.

Go to the official website and download the LTS version for your OS – Windows, macOS or Linux. This contains the latest features and important bug fixes.

Run the installer and verify installation from your terminal:

node -v

(You‘ll see something like v16.14.2)

Step 2: Download Visual Studio Code

Get VS Code for your platform here:

code.visualstudio.com/download

Install it like any other app. Launch VS Code after this – its clean UI will greet you!

Step 3: Create your First JS Project

Okay, we have our tools in place. Time to write JavaScript!

Let‘s create a simple project directory first:

  • Launch the Integrated Terminal in VS Code (Ctrl/Cmd+")
  • Make a new folder:
mkdir my-amazing-project 
  • And navigate (cd) inside this folder:
cd my-amazing-project

Awesome! Our environment is now ready for us to code JavaScript in VS Code.

Writing and Running JavaScript in VS Code

Let‘s start with a simple JS program that prints a welcome message.

💡 Inside your project folder, create a file hello.js

Add this code to print "Hello VS Code!":

console.log("Hello VS Code!");

Let‘s run our first line of JavaScript code:

  • Go to the Integrated Terminal and run:
node hello.js  

You‘ll see "Hello VS Code!" printed there! 🎉

Now let‘s build something more useful. We‘ll create a program to calculate a tip based on the bill amount.

Create another file tip-calculator.js

// Calculate tip 
function calculateTip(billAmount, tipPercentage) {

  // Calculate tip  
  const tip = billAmount * tipPercentage / 100;

  // Add tip to total bill  
  const total =  billAmount + tip;

  console.log(
    `Bill Amount: ${billAmount} 
    Tip Percentage: ${tipPercentage}%
    Tip Amount: ${tip}
    Total Bill: ${total}`
  );

}

// Example usage:  
calculateTip(100, 15); 

The code above:

  • Defines a calculateTip() function
  • Accepts bill amount and tip percentage
  • Calculates tip value and total bill
  • Prints an itemized payment breakdown

Let‘s run it:

node tip-calculator.js

Works perfectly! 🙌

We‘ll explore more examples with functions, objects, loops, promises and async/await.

We‘ll also see how VS Code helps debug errors and analyze execution flows.

Debugging JavaScript Code

No one‘s code works flawlessly from the start! Let‘s see how debugging works.

In tip-calculator.js add a deliberate bug:

const total = billAmount + tip; // Oops removed variable names  

Run the code again:

node tip-calculator.js

🆘 We hit a ReferenceError! But see how VS Code highlights the problematic line inline?

Let‘s debug:

  • Click Debug icon
  • Add a breakpoint on line 2
  • Start debugging and step through the code execution

You can analyze all variable values in the sidebar and fix issues easily. Debugging tools save the day!

Best Practices for Quality JavaScript Code

As your programs grow bigger, here are some tips:

1. Break Code into Reusable Modules

Ideal programs have loosely coupled modules that can be reused. Eg:

services/
  tip-calculator.js 
utils/
  math.js
server.js

2. Lint Your Code with ESLint

Install the ESLint extension. It will fix issues and ensure code quality.

3. Use Prettier to Auto-format Code

Formats all code instantly to match style guidelines. No more messy indentations!

4. Automate Builds with Task Runners

Task runners like Gulp let you automate code transpiling, minification, testing and more.

5. Always Use Source Control with Git!

Which brings us to…

Pushing Code to GitHub

To share your code online and collaborate:

1. Create a GitHub Repository

Sign up on GitHub.com and create a new repository.

2. Initialize Local Git Repository

In your project in VS Code terminal, type git init. This turns it into a Git repo.

3. Commit Changes

Stage files and commit snapshots as you progress.

Eg:

git add .
git commit -m "Refactor functions" 

4. Connect Remote and Push Code

Link the local repo to remote GitHub repo.

git remote add origin <github_url>
git push origin master  

Just like that, your code is on GitHub! 🚀

Now you can leverage GitHub for:

  • Hosting web apps
  • Collaborating via pull requests
  • Tracking commit history
  • And so much more!

Level Up Your JavaScript Mastery

I hope you‘re able to confidently code JavaScript in VS Code now.

To take your skills to the next level, here are amazing resources:

Books

Courses

  • Scrimba – Fun video-based courses to get hands-on with frameworks like React and VueJS.

  • Frontend Masters – Expert-led JavaScript and web development courses with coding challenges.

Documentation

Let‘s Recap

We covered a lot of ground in this 4,000+ words guide!

Here‘s what you now know:

  • How VS Code provides exceptional JavaScript support
  • Setting up a coding environment with VS Code and Node.js
  • Creating a JS project and running different programs
  • Debugging code errors like a pro
  • Following coding best practices for clean quality code
  • Pushing source code to GitHub for sharing and collaboration
  • Leveling up JS skills through books, tutorials and courses

You‘re now fully equipped to build interactive web apps, program robots, automate tasks and bring all your wildest ideas to life using JavaScript and Visual Studio Code!

So open up VS Code, and let‘s code something amazing today! 🚀