Writing & Running JavaScript Code in VS Code

This comprehensive guide will walk you through setting up your development environment in Visual Studio Code, writing your first JavaScript program, and running it. You'll also learn how to use extensions, debug your code, and manage your code structure. Plus, we'll cover basic JavaScript syntax and version control with Git.

Welcome to the world of JavaScript development with Visual Studio Code (VS Code)! Whether you're a complete beginner or just starting with JavaScript, this guide will help you set up your development environment, write your first JavaScript program, and get a solid foundation in some of the basic syntax and features of JavaScript. By the end of this guide, you'll have a good understanding of how to write, run, and debug JavaScript code in VS Code, and even start using version control with Git.

Getting Started

Let's begin by setting up Visual Studio Code on your computer. If you're new to coding, you might be excited to get started right away, but take a moment to understand why setting up your environment is important. Think of this as setting up your workspace in a real-world scenario, where everything is organized and ready to go before you start.

Installing VS Code

Downloading VS Code

First, you'll need to download Visual Studio Code. Follow these steps:

  1. Visit the official VS Code website.
  2. Click on the "Mac" button to download for Mac, "Windows" for Windows, or follow instructions for Linux.

Downloading VS Code is like gathering the materials you need for a project. Just as you wouldn't start building a house without a hammer, you won't start coding without a good text editor.

Installing VS Code

After downloading the installer, it's time to install VS Code:

  1. Open the downloaded file and follow the on-screen instructions to install.
  2. Once installed, launch VS Code.

Installing VS Code is like assembling your toolkit before starting a project. With all your tools in place, you have everything you need to get started.

Setting Up Your Development Environment

Installing Required Extensions

Once VS Code is open, it's time to install some helpful extensions. Extensions in VS Code are like plugins that can enhance your coding experience.

  • JavaScript (ES6) code snippets: Speeds up your coding with pre-written snippets.
  • Live Server: Automatically refreshes your browser every time you save a file.

To install extensions:

  1. Click on the Extensions icon on the sidebar (four squares).
  2. Search for "JavaScript (ES6) code snippets" and install it.
  3. Search for "Live Server" and install it.

Think of these extensions as power tools that make your job easier. Just as a carpenter wouldn't start a project without a saw, a developer wouldn't want to start without these extensions.

Writing JavaScript Code

With your development environment set up, it's time to start writing some code! Let's go through the process step by step.

Creating a New Project Folder

Opening a Folder in VS Code

  1. Click on "File" in the menu bar and select "Open Folder."
  2. Choose a location on your computer where you want to create your project folder.
  3. Create a new folder (for example, "my-first-javascript-project") and select it.

Opening a folder in VS Code is like choosing a workspace in a physical project. Just as you wouldn't start a woodworking project on a cluttered table, you wouldn't want to start a coding project in a disorganized folder.

Initializing a JavaScript File

Naming Conventions

When naming your JavaScript files, it's important to follow conventions:

  • Use lowercase letters.
  • Use hyphens or underscores to separate words.
  • Avoid spaces (for example, "index.js" or "my-script.js").

This makes your file names consistent and easier to read, much like how you'd label your tools in a tool shed.

Writing Your First JavaScript Code

Writing a "Hello, World!" Program

Let's write a simple "Hello, World!" program to get started.

  1. In the Explorer sidebar, right-click on the folder and select "New File."
  2. Name the file "index.js."
  3. Write the following code in the new file:
    // This is a comment
    console.log("Hello, World!");
    

This code is like a blueprint for a simple machine. The console.log function is like a printing press that outputs "Hello, World!" to the console every time the code runs.

Saving Your File

Always save your files frequently to avoid losing your work. You can save by clicking on the disk icon in the top bar or by pressing Ctrl + S on Windows/Linux or Cmd + S on Mac.

Think of saving as taking a snapshot of your work at every stage. It's essential to keep these snapshots throughout your project.

Running JavaScript Code

Running your JavaScript code allows you to see the output of your programs. There are several ways to do this in VS Code. Let's explore a few methods.

Using the Terminal

Opening the Terminal in VS Code

  1. Click on "Terminal" in the top menu bar and select "New Terminal."

Opening the terminal is like turning on a light in your workshop. Just as you wouldn't start a project without light, you won't run your code without a terminal.

Running a JavaScript File with Node.js

  1. Make sure you have Node.js installed on your computer. You can download it from the official Node.js website.
  2. In the terminal, type node index.js and press Enter.

This command tells Node.js to run the index.js file. If everything is set up correctly, you should see "Hello, World!" printed in the terminal.

Running your code is like testing a prototype. Just as you wouldn't build a car without test driving it, you shouldn't finish writing a program without running it.

Using the Built-in Preview

Using Live Server for Real-time Preview

Live Server is an extension that lets you see your code changes in real-time without refreshing the browser manually.

  1. Install the "Live Server" extension as mentioned above.
  2. Right-click on your HTML file (if you have one) and select "Open with Live Server." If you don't have an HTML file, you can create one like this:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>My First JavaScript Project</title>
    </head>
    <body>
        <script src="index.js"></script>
    </body>
    </html>
    
  3. Save the file and open it with Live Server.
  4. Check your browser for the "Hello, World!" message.

Using Live Server is like having a live demo of your project. Just as a chef previews a dish before serving it, you should preview your code.

Previewing HTML Pages with JavaScript

With the HTML file set up as shown above and the script tag linking to your index.js, you can see the effects of your JavaScript code directly in the browser.

Debugging JavaScript Code

Debugging is an essential part of programming. It's like checking your tools before starting a project to ensure everything works.

Setting Breakpoints

  1. Open your index.js file.
  2. Click on the line number next to the console.log("Hello, World!"); line to set a breakpoint. You should see a red dot appear.

Setting breakpoints is like putting markers on your tools. Just as a carpenter would mark a piece of wood before cutting it, you mark your code to see where it might be going wrong.

Using the Debugger

  1. Click on the Run icon on the sidebar.
  2. Click on "create a launch.json file" and select "Node.js."
  3. Click on the green play button to start debugging.

Using the debugger is like testing your tools on a piece of scrap wood before using them on the real project. Just as you wouldn't want to waste precious materials on trial runs, you wouldn't want to make mistakes in production code.

Inspecting Variables and Call Stack

While debugging, you can inspect variables and see the call stack to understand how your code is running.

  1. Start debugging by pressing the green play button.
  2. When the breakpoint is hit, the execution will pause, and you can inspect variables and the call stack in the debugging panel.

Inspecting variables and the call stack is like checking the measurements and fitting of a piece of furniture. Just as you wouldn't want to install a piece of furniture without checking its dimensions, you shouldn't create a complex script without understanding its components.

Organizing and Managing Code

Good organization keeps your codebase clean and easy to navigate, much like how a well-organized toolbox keeps you efficient.

Using Comments

Single Line Comments

Comments help you and others understand your code. Single line comments start with //.

// This is a single line comment
console.log("Hello, World!");

Multi-line Comments

Multi-line comments start with /* and end with */.

/*
This is a multi-line comment.
It can span multiple lines.
*/
console.log("Hello, World!");

Comments are like notes you leave in your workshop. Just as you wouldn't start a project without notes, you shouldn't write code without comments.

Understanding File Structure

Creating Subfolders

  1. In the Explorer sidebar, right-click on your project folder and select "New Folder."
  2. Name the folder something relevant (for example, "scripts").
  3. Move your index.js file into this new folder.

Creating subfolders is like organizing tools in different drawers. Just as you wouldn't leave all your tools in one place, you shouldn't keep all your files in one folder.

Organizing Files

Organizing your files is crucial as projects grow. Follow these tips:

  • Keep all your JavaScript files in a folder named "scripts."
  • Keep all your CSS files in a folder named "styles."
  • Keep all your images in a folder named "images."

Organizing your files is like organizing a bookshelf. Just as you wouldn't randomly place books on a shelf, you shouldn't randomly place files in a folder.

Naming Conventions

Variables and Functions

Follow these conventions for naming:

  • Use camelCase for variables and functions. For example, myVariable, myFunction.
  • Use PascalCase for class names. For example, MyClass.

Naming conventions are like labeling your tools. Just as you wouldn't label a hammer as "screwdriver," you shouldn't name your variables or functions in a way that's unclear.

Files and Folders

  • Use lowercase letters.
  • Use hyphens or underscores to separate words.
  • Avoid spaces and special characters.

Organizing files and folders is like organizing a library. Just as you wouldn't put a book on the wrong shelf, you shouldn't put a file in the wrong folder.

Basic JavaScript Syntax Review

Understanding basic syntax is like knowing the ABCs of writing. Without knowing the basics, you wouldn't be able to write complex code.

Variables

Declaring Variables

Variables store data in your program. You can declare variables using let, const, or var.

let myVariable = "Hello";
const anotherVariable = "World";
var oldVariable = "Goodbye";

These declarations are like containers that hold different items. Just as you wouldn't put a hammer in a toolbox meant for screws, you shouldn't use const for variables that are going to change.

Data Types

JavaScript has several data types:

  • Numbers: 1, 2.5
  • Strings: "Hello", 'World'
  • Booleans: true, false
  • Arrays: [1, 2, 3]
  • Objects: {name: "John", age: 30}

Data types are like different materials you use in a project. Just as you wouldn't use wood for an electrical project, you shouldn't use the wrong data type in JavaScript.

Functions

Declaring Functions

Functions are blocks of code that perform a specific task. You can declare functions using function or arrow function syntax.

// Function declaration
function myFunction() {
    console.log("Hello, World!");
}

// Arrow function syntax
const myArrowFunction = () => {
    console.log("Hello, World!");
};

Functions are like blueprints for machines. Just as a blueprint tells you how to build a machine, a function tells your program how to perform a task.

Calling Functions

Functions need to be called to execute.

myFunction();          // Outputs: Hello, World!
myArrowFunction();     // Outputs: Hello, World!

Calling functions is like instructing someone to build a machine using the blueprint. Just as you wouldn't build a machine without an instruction, you shouldn't run a function without calling it.

Loops

For Loop

A loop runs a block of code multiple times.

for (let i = 0; i < 5; i++) {
    console.log(i);
}
// Outputs: 0 1 2 3 4

Loops are like repeating a task multiple times. Just as you wouldn't hammer a nail in the same spot five times manually, you wouldn't write the same code five times without a loop.

While Loop

A while loop continues to run as long as a condition is true.

let i = 0;
while (i < 5) {
    console.log(i);
    i++;
}
// Outputs: 0 1 2 3 4

While loops are like setting a condition to keep working. Just as a painter wouldn't stop painting a wall until it's completely painted, a while loop doesn't stop until the condition is met.

Conditionals

If Statement

An if statement runs a block of code only if a condition is true.

let weather = "sunny";
if (weather === "sunny") {
    console.log("Let's go to the beach!");
}
// Outputs: Let's go to the beach!

If statements are like making decisions. Just as you wouldn't go to the beach in rainy weather, you wouldn't run a specific block of code unless the conditions are right.

Switch Statement

A switch statement is used to execute different blocks of code based on different conditions.

let day = "Friday";
switch (day) {
    case "Monday":
        console.log("Start of the week.");
        break;
    case "Friday":
        console.log("End of the week.");
        break;
    default:
        console.log("In the middle of the week.");
}
// Outputs: End of the week.

Switch statements are like choosing from multiple options. Just as you wouldn't pick a hammer for every task, you wouldn't use an if statement for every condition.

Arrays and Objects

Creating Arrays

Arrays store multiple values in a single variable.

let fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // Outputs: apple

Arrays are like boxes that hold multiple items. Just as you wouldn't put multiple screws in the same box as screws, you shouldn't put unrelated data in the same array.

Creating Objects

Objects store data in key-value pairs.

let person = {
    name: "John",
    age: 30,
    greet: function() {
        console.log("Hello, my name is " + this.name + ".");
    }
};
person.greet(); // Outputs: Hello, my name is John.

Objects are like detailed descriptions of items. Just as a blueprint has detailed instructions, an object has detailed information about a specific entity.

DOM Manipulation

Accessing Elements

You can manipulate the Document Object Model (DOM) to change the HTML dynamically.

// In your index.js file
document.getElementById("demo").innerHTML = "Hello, World!";
<!-- In your index.html file -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DOM Manipulation</title>
</head>
<body>
    <p id="demo"></p>
    <script src="scripts/index.js"></script>
</body>
</html>

DOM manipulation is like changing parts of a machine. Just as you wouldn't replace an engine without inspecting it, you shouldn't change parts of your HTML without manipulation.

Modifying Elements

You can also modify elements directly.

document.getElementById("demo").style.color = "red";
document.getElementById("demo").style.fontSize = "20px";

This code changes the color and font size of the element. Just as you wouldn't change the color of a wall without a paintbrush, you shouldn't change the style of an element without the right properties.

Version Control with Git (Optional)

Using version control is like keeping a journal of your project. Just as you wouldn't start a big project without a plan, you shouldn't start a coding project without version control.

Initializing a Git Repository

Creating a .gitignore File

Once you have Git installed, initialize a repository.

  1. Open the terminal.
  2. Navigate to your project folder.
  3. Type git init to initialize a repository.
  4. Create a .gitignore file to tell Git which files to ignore (for example, node_modules).
echo "node_modules" > .gitignore

Creating a .gitignore file is like making a list of tools you don't need in your toolbox. Just as you wouldn't keep unused tools in your toolbox, you shouldn't track unnecessary files in your repository.

Basic Git Commands

Adding Files

To add files to your repository, use the git add command.

git add .

Adding files is like adding materials to your project. Just as you wouldn't start building a project without materials, you shouldn't start tracking files without adding them to your repository.

Committing Changes

To commit changes, use the git commit command.

git commit -m "Initial commit"

Committing changes is like documenting each step of your project. Just as you wouldn't forget to document a crucial step, you shouldn't forget to commit your changes.

Pushing to a Remote Repository

Push your changes to a remote repository using the git push command.

git remote add origin https://github.com/yourusername/your-repo.git
git push -u origin master

Pushing changes is like sharing your project with others. Just as you wouldn't keep a project a secret, you shouldn't keep your code changes a secret.

Connecting to GitHub

Creating a GitHub Repository

  1. Go to GitHub and log in.
  2. Click on the "+" icon and select "New repository."
  3. Follow the instructions to create a new repository.

Creating a GitHub repository is like showcasing your project to the world. Just as you wouldn't start a project without an audience, you shouldn't start a project without a repository.

Cloning the Repository to VS Code

To clone a repository to VS Code:

  1. Open the terminal in VS Code.
  2. Use the git clone command with the repository URL.
    git clone https://github.com/yourusername/your-repo.git
    

Cloning a repository is like copying a blueprint. Just as you wouldn't start a project without a blueprint, you shouldn't start a project without a repository.

Conclusion

You made it through setting up your development environment, writing your first JavaScript program, running your code, and even using version control. This journey is just the beginning, and JavaScript has a lot more to offer.

Remember, practice is key. The more you code, the better you'll get. Happy coding!

By the end of this guide, you should have a solid foundation in setting up your development environment in VS Code, writing JavaScript code, running it, and debugging. You're now ready to take your JavaScript skills to the next level and start building more complex projects. Keep exploring, and happy coding!