Hello World

Your First JavaScript Program

Project Setup

Create a JavaScript Project

Let's get started by creating and opening a new hello-world project:

  1. From the Command Line (~/wcci/code) make a new directory and navigate into it: mkdir hello-world && cd hello-world
  2. Open this project in VSCode: code .

VS Code

VSCode logo

VS Code is our Integrated Development Environment (IDE). VS Code includes a bunch of really helpful tools that allow us to write our JS code much more easily.

Create a JavaScript file

New Java Class

• Inside of your newly created project, create a new file by clicking the New File icon next to your projects name

• The naming convention of a standard JavaScript file is kebab-case: hello-world.js

• Now you've got a file you can write some JS in!

Let's Add Some Code!

JavaScript Functions

You want to avoid having uncontextualized JS code just floating around your file system. To avoid this, we use functions. Let's take a look:

function sayHelloWorld() {
  // TODO: add code to say `Hello World`
}

Note that any code we use to actual print Hello World is going to be housed in this function.

Curly Brackets

Curly brackets ({ and }) indicate code blocks in JavaScript. An opening curly bracket ({) must always, always, always have a corresponding closing curly bracket (}).

Seen here in our function

function sayHelloWorld() {
  // TODO: add code to say `Hello World`
}

Comments

We can add comments to our code to explain it. They don't do anything.

function sayHelloWorld() {
  // TODO Auto-generated method stub
}

Hello World!

A common first program for people to write in a language is a program that says "Hello, World!" That's just what we'll do. Change your code to look like the following:

function sayHelloWorld() {
  console.log("Hello World!");
}

// We also need to call this function
sayHelloWorld();

log will 'log' or print a message to our console. Here we are sending a log message to console with the content "Hello World!"

Let's run it, and see what happens!

A Simple Greeting

After a quick save, navigate back to your command line and let's execute our program!

Run the following command from the root of your project: node hello-world.js

You should see "Hello World!" printed to the console! You've just created your first JavaScript program!

Next Steps

JavaScript is a weakly-typed language. The type of "Hello, World!" is String:

console.log("Hello World!");

We can also do this with other Strings:

console.log("I can code it!");

Other Data Types

We can also display numbers and more complex expressions.

console.log(42);
console.log(1.23);
console.log([1, 2, 3]);

Try a few of your own! We'll talk about other data types and expressions in days to come.