© We Can Code IT, LLC
Let's get started by creating and opening a new hello-world
project:
~/wcci/code
) make a new directory and navigate into it: mkdir hello-world && cd hello-world
code .
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.
• 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!
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 ({
and }
) indicate code blocks in JavaScript. An opening curly bracket ({
) must always, always, always have a corresponding closing curly bracket (}
).
function sayHelloWorld() {
// TODO: add code to say `Hello World`
}
We can add comments to our code to explain it. They don't do anything.
function sayHelloWorld() {
// TODO Auto-generated method stub
}
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!
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!
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!");
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.