Module 5: Hello, JavaScript!
Objective: dive into development with JavaScript by running a simple program in a variety of environments.
- What's ahead
- JavaScript: the programming language of the web
- Hello, world!
- Developer tools
- Local development
- Explanation of the greeting program
- Done!
What's ahead
I hope making a game in HTML and CSS was a nice appetizer for the main course: making your own game in JavaScript! Here's the plan for the rest of the semester:
- Spend the next few weeks learning the basics of programming by making a "block dodger" game in JS. We'll work in teams and as a class.
- Spend the remaining seven weeks building your own game (or web app!) in JS, working in groups.
JS is going to be a significant increase in difficulty from HTML and CSS, but we're also going to spend more time on it and ensure everyone understands the important concepts as we go.
Games can be challenging to program, so getting as solid on the basics as you can is your best bet: try to spend as much time as possible on Codecademy! It's sort of like writing a short story; you want to spend time worrying about the high-level stuff like plot and character development and not on low-level stuff like spelling, grammar, and punctuation mistakes.
Here's the block dodger game we're going to build together:
See the Pen block dodger by ggorlen (@ggorlen) on CodePen.
A word of caution: programming can be complex, and sometimes bits of code I'm going to show you have to be taken on faith, at least at first. These bits are generally there to get the app to function for us, but might involve a more advanced concept than you may be ready to see. Don't be intimidated--just type it in, read a brief explanation, then we'll revisit these concepts again when you'll have the context and conceptual arsenal for understanding them.
JavaScript: the programming language of the web
JS is one of the easiest programming languages to learn, but is also extremely powerful. It's the only language that runs directly in web browsers. The cool thing about this is that when you visit a website which has JS, you can read it just like HTML and CSS using the "view page source" feature on your browser (as discussed in module 1). It also means that JS has a monopoly on front-end programming, which guarantees that 1) an enormous amount of time and effort goes into making it great, and 2) it will likely be relevant for some time to come.
There is so much theory behind programming, and I love to discuss it and think about how it all works. But we don't really have time to get too detailed, unfortunately, so I'll leave it to you to pursue your own research as you feel inclined. If I get too off-topic, just tell me to get back on track!
Oh yeah: you may have heard of this "Java" thing:
That's true to a large extent; however, once you learn a programming language, all of the basics transfer to any other language, so in that sense Java and JS are not all that different. Language choice boils down to picking the right tool for the job, and for front-end web programming, JS is the only tool.
Hello, world!
With that introduction, let's dive in to doing programming in JS. The first orders of business are making sure JS is working and getting comfortable with our development environment(s).
Hello, world! is the first program you'll write in any language, so let's go ahead and write it:
console.log("Hello, world!");
This program tells JS to print the text "Hello, world!" in the browser's console. Let's execute this program at repl.it. Repl is an easy way to run snippets of JS code, so we'll be using it often. Once you've run the program, try changing the text inside the quotation marks, and run it again. Tip: whenever you have some new code, always try making a change or three to convince yourself of how it works.
Developer tools
Now that we have a working JS program, let's run it in a few different environments
and learn about our browser's developer tools. Developer tools are included in
every major browser, but opening them is platform- and browser- specific; ask
Google "how do i open developer tools in
os x and browser y?" where x is your operating system (Mac/Windows)
and y is your browser (Chrome, Firefox). In particular, we'll be using the console component of
the dev tools, which is a place that can interactively execute JS code, display errors,
and show output from console.log()
statements.
With your console open, try running the "Hello, world!" program by typing it right into the console. Once that works, also try running the program on Codepen. The output will be visible in the browser's console as well as Codepen's mini-console.
Local development
Now that we know how to make JS output something in the browser, let's turn our attention to running JS code inside an HTML file. As with CSS, we can include JS in a HTML file in a few ways:
- inside of
<script>
tags - as an external
.js
script file - in-line, inside of an HTML element
We'll be using external .js
files mostly, and here's how:
-
Create two files in the same directory:
greeting.html
andgreeting.js
. -
Inside of
greeting.js
, add the following JS code (it uses new syntax which I'll explain shortly):// Ask the user for their name let visitorName = prompt("What is your name?"); // Greet the user alert("Hello, " + visitorName + "!");
-
Inside of
greeting.html
, add the following code, which includes the JS script in the HTML code; the script executes when the page is loaded:<html> <head> <title>Greeting page</title> </head> <body> <script src="greeting.js"></script> </body> </html>
-
Open
greeting.html
in a browser and enter your name into the prompt. Consider yourself greeted.
If you wish, feel free to try writing this same program on Codepen.
Codepen fills in the basic <html>
, <head>
, <body>
tags automatically and connects the three scripts together, so all you have to write is the JS code.
Same thing on repl.it--just the JS is enough.
Explanation of the greeting program
Cool. Now that you've executed a couple of programs in a variety of environments, let's take a moment to examine how the "greeting" program works, then we'll call it a day. Let's start with the first two lines:
// Ask the user for their name
let visitorName = prompt("What is your name?");
The first line is a comment, but with a slightly different syntax from the CSS comments. CSS
comments work in JS too; they're called multi-line comments, while the //
comment
is a single-line comment.
The second line has a lot of action in it. Let's start with prompt("What is your name?");
.
This line calls a function
that was built into the standard JS library. Functions are bits of code that serve a single, explicit
purpose and can be called, or executed, again and again. The prompt
function makes
a dialog box pop up and waits for the user to input text and press "OK."
Two cool things about functions which are on display in the above example:
-
You can specify parameters which go inside the
( )
parenthesis after the function name. Parameters change how the function behaves during a call. In this case,prompt()
allows the programmer to tell it which string, or bit of text, it should display in the dialog box. Try changing the"What is your name?"
line to something else and see what happens. Just make sure to keep the quotes. Can you identify the parameter forconsole.log("Hello, world!");
? -
Functions can return information from them when they are called. In this case, the function returns a string, which is whatever the user entered into the dialog box.
Now that the prompt("What is your name?");
component is a little clearer, let's discuss the let visitorName =
part. let
is a keyword in JS which creates a new
variable, or
named storage space for a piece of data. We can store anything in this variable and retrieve and manipulate it
later on in our program. We can name the variable any series of letters, numbers, or underscores we want, provided
that it doesn't begin with a number. There are some conventions for naming variables in JS. For now,
write all variable names in camelCase--the
first word is lowercase and all subsequent words begin with an uppercase letter.
Another thing to note is that var
is another way
to declare a variable which you may see used, and you are welcome to use yourself
instead of let
. The difference is too small to worry
about just yet.
As for the =
equals sign, this isn't a measure of equality, but rather an
assignment operator. Assignment takes the value on the right of the
=
and sticks it into the variable on the left.
If I run the program and type "bob" into the prompt, that string gets
stored in the visitorName
variable.
OK, it's all smooth sailing for the next bit of code:
// Greet the user
alert("Hello, " + visitorName + "!");
Here's another JS built-in function called alert()
, which is the annoying
pop-up box you've probably encountered before. You (hopefully) won't be using
prompt()
and alert()
much,
but they're handy for little test code like this. alert()
works
by taking a string parameter and makes that the text that pops up. It doesn't return any value.
The more interesting part of the second line of code is what's going on inside the function's
parameter. The +
symbols are concatenating, or joining,
the values of three strings, "Hello, ", "bob", and "!" into one string: "Hello, bob!" (assuming
the user entered "bob" into the prompt), which is what gets sent into the
alert()
function for display.
Done!
Great! You learned a ton about JS today. Let it all sink in, play with the greeting program, and work on basics at Codecademy. A lot of programming stuff won't make sense at first, but stick with it and it'll become second nature. See you next time, when we'll begin working with graphics and start on our block dodger game!