JavaScript gives you superpowers. The true programming language of the web, JavaScript lets you add behavior to your web pages. No more dry, boring, static pages that just sit there looking at you—with JavaScript, you’ll be able to reach out and touch your users, react to interesting events, grab data from the web to use in your pages, draw graphics right in your web pages and a lot more. And once you know JavaScript you’ll also be in a position to create totally new behaviors for your users.
You’ll be in good company too. JavaScript’s not only one of the most popular programming languages, it’s also supported in all modern browsers and is used in many environments outside of the browser. More on that later; for now, let’s get started!
If you’re used to creating structure, content, layout and style in your web pages, isn’t it time you add a little behavior as well? After all, there’s no need for the page to just sit there. Great pages should be interative and dynamic. That’s where JavaScript comes in. Let’s start by taking a look at how JavaScript fits into the web page ecosystem:
JavaScript is fairly unique in the programming world. With your typical programming language you have to write it, compile it, link it and deploy it. JavaScript is much more fluid and flexible. With JavaScript all you need to do is write JavaScript right into your page, and then load it into a browser. From there, the browser will happily begin executing your code. Let’s take a closer look at how this works:
First things first. You can’t get very far with JavaScript if you don’t know how to get it into a web page. So, how do you do that? Using the <script>
element of course!
Let’s take a boring old, garden-variety web page and add some dynamic behavior using a <script>
element. Now, at this point, don’t worry too much about the details of what we’re putting into the <script>
element—your goal right now is to get some JavaScript working.
Go ahead and type this page into a file named “behavior.html”. Drag the file to your browser (or use File > Open) to load it. What does it do? Hint, you’ll need to wait five seconds to find out.
With HTML and CSS you can create some great looking pages. But once you know JavaScript, you can really expand on the kinds of pages you can create.
Knowing JavaScript might increase the size of your paycheck too!
So much so, in fact, you might actually start thinking of your pages as applications (or even experiences!) rather than mere pages.
Now, you might be saying, “I already know that, why do you think I’m reading this book?” Well, we actually wanted to use this opportunity to have a little chat about learning JavaScript. If you already have a programming language or scripting language under your belt, then you have some idea of what lies ahead. However, if you’ve mostly been using HTML & CSS to date, you should know that there is something fundamentally different about learning a programming language.
With HTML & CSS what you’re doing is largely declarative—for instance, you’re declaring, say, that some text is a paragraph or that all the HTML elements in the “sale” class should be colored red. With JavaScript you’re adding behavior to the page, and to do that you need to describe computation. You’ll need to be able to describe things like, “compute the user’s score by summing up all the correct answers” or “do this action ten times” or “when the user clicks on that button play the you-have-won sound” or even “go off and get my latest tweet, and put it in this page.”
To do those things you need a language that is quite different from HTML or CSS. Let’s see how...
When you create HTML you usually mark upg text to give it structure; to do that you add elements, attributes and values to the text:
CSS is a bit different. With CSS you’re writing a set of rules, where each rule selects elements in the page, and then specifies a set of styles for those elements:
With JavaScript you write statements. Each statement specifies a small part of a computation, and together, all the statements create the behavior of the page:
You might have noticed that JavaScript statements usually involve variables. Variables are used to store values. What kinds of values? Here are a few examples:
There are other values that variables can hold beyond numbers, strings and booleans, and we’ll get to those soon enough, but, no matter what a variable contains, we create all variables the same way. Let’s take a little closer look at how to declare a variable:
We say optionally, because if you want, you can create a variable without an initial value, and then assign it a value later. To create a variable without an initial value, just leave off the assignment part, like this:
So far, we’ve used the keyword let
to declare our variables. And that’s typically what we want to do with variables whose values can vary, or in other words, change their value over time. For instance, if we use let
to declare the variable winners
, assign it the value 2, we can change the value in winners
later to be 3 if another winner comes along:
Sometimes, however, we do not want the values in our variables to vary at all. There are situations in which we might want to give a name to a value that we’ll use in our code, but we don’t ever want that value to change. Here’s a good example: the radius of planet Earth. It might be handy to assign this value to a variable so we can use EARTH_RADIUS
instead of the number in our code. We don’t want anyone to come along and change this value accidentally, so how can we make sure the value of EARTH_RADIUS
never changes? We can use a constant instead of a variable, like this:
You know variables have a name, and you know they have a value.
You also know some of the things a variable can hold are numbers, strings and boolean values.
But what can you call your variables? Is any name okay? Well no, but the rules around creating variable names are simple: just follow the two rules below to create valid variable names:
Start your variables with a letter, an underscore or a dollar sign.
After that, use as many letters, numeric digits, underscores or dollar signs as you like.
Oh, and one more thing; we really don’t want to confuse JavaScript by using any of the built-in keywords, like let or function or false, so consider those off limits for your own variable names. We’ll get to some of these keywords and what they mean throughout the rest of the book, but here’s a list to take a quick look at:
break
case
catch
class
const
continue
debugger
default
delete
do
else
enum
export
extends
false
finally
for
function
if
implements
import
in
instanceof
interface
let
new
package
private
protected
public
return
static
super
switch
this
throw
true
try
typeof
var
void
while
with
yield
To truly express yourself in JavaScript you need expressions. Expressions evaluate to values. You’ve already seen a few in passing in our code examples. Take the expression in this statement for instance:
If you’ve ever taken a math class, balanced your checkbook or done your taxes, we’re sure these kinds of numeric expressions are nothing new.
There are also string expressions; here are a few:
We also have expressions that evaluate to true or false, otherwise known as boolean expressions. Work through each of these to see how you get true or false from them:
And expressions can evaluate to a few other types; we’ll get to these later in the book. For now, the important thing is to realize all these expressions evaluate to something: a value that is a number, a string or a boolean. Let’s keep moving and see what that gets you!
You do a lot of things more than once:
Lather, rinse, repeat...
Wax on, wax off...
Eat candies from the bowl until they’re all gone.
Of course you’ll often need to do things in code more than once, and JavaScript gives you a few ways to repeatedly execute code in a loop: while, for, for in and forEach. Eventually, we’ll look at all these ways of looping, but let’s focus on while for now.
We just talked about expressions that evaluate to boolean values, like scoops > 0
, and these kinds of expressions are the key to the while statement. Here’s how:
Seeing as this is your first while loop, let’s trace through a round of its execution to see exactly how it works*. Notice we’ve added a declaration for scoops to declare it, and initialize it to the value 5.
Now let’s start executing this code. First we set scoops to five.
After that we hit the while statement. When we evaluate a while statement the first thing we do is evaluate the conditional to see if it’s true or false.
Because the conditional is true, we start executing the block of code. The first statement in the body writes the string “Another scoop! <br>” to the browser.
* To follow along, grab the code for this chapter from http://wickedlysmart.com/hfjs and drag the file icecream.html into your browser.
The next statement subtracts one from the number of scoops and then sets scoops to that new value, four.
That’s the last statement in the block, so we loop back up to the conditional and start over again.
Evaluating our conditional again, this time scoops is four. But that’s still more than zero.
Once again we write the string “Another scoop! <br>” to the browser.
The next statement subtracts one from the number of scoops and sets scoops to that new value, which is three.
That’s the last statement in the block, so we loop back up to the conditional and start over again.
Evaluating our conditional again, this time scoops is three. But that’s still more than zero.
Once again we write the string “Another scoop! <br>” to the browser.
And as you can see, this continues... each time we loop, we decrement (reduce scoops by 1), write another string to the browser, and keep going.
And continues...
Until the last time... this time something’s different. Scoops is zero, and so our conditional returns false. That’s it folks; we’re not going to go through the loop anymore, we’re not going to execute the block. This time, we bypass the block and execute the statement that follows it.
Now we execute the other document.write, and write the string “Life without ice cream isn’t the same”. We’re done!
if (cashInWallet > 5) { order = "I’ll take the works: cheeseburger, fries and a coke"; } else { order = "I’ll just have a glass of water"; }
You’ve just seen how you use a conditional to decide whether to continue looping in a while
statement. You can also use boolean expressions to make decisions in JavaScript with the if
statement. The if
statement executes its code block only if a conditional test is true. Here’s an example:
With an if
statement we can also string together multiple tests by adding on one or more else if
’s, like this:
You can string together as many if
/else
statements as you need, and if you want one, even a final catch-all else
, so that if all conditions fail, you can handle it. Like this:
We’ve been talking about making your pages more interactive, and to do that you need to be able to communicate with your user. As it turns out there are a few ways to do that, and you’ve already seen some of them. Let’s get a quick overview and then we’ll dive into these in more detail throughout the book:
As you’ve seen, the browser gives you a quick way to alert your users through the alert
function. Just call alert
with a string containing your alert message, and the browser will give your user the message in a nice dialog box. A small confession though: we’ve been overusing this because it’s easy; alert
really should be used only when you truly want to stop everything and let the user know something.
Think of your web page as a document (that’s what the browser calls it). You can use a function document.write
to write arbitrary HTML and content into your page at any point. In general, this is considered bad form, although you’ll see it used here and there. We’ve used it a bit in this chapter too because it’s an easy way to get started.
We’re using these three methods in this chapter.
Every JavaScript environment also has a console that can log messages from your code. To write a message to the console’s log you use the function console.log
and hand it a string that you’d like printed to the log (more details on using console log in a second). You can view console.log
as a great tool for troubleshooting your code, but typically your users will never see your console log, so it’s not a very effective way to communicate with them.
The console is a really handy way to help find errors in your code! If you’ve made a typing mistake, like missing a quote, JavaScript will usually give you an error in the console to help you track it down.
This is the big leagues; this is the way you want to be interacting with your page and users—using JavaScript you can access your actual web page, read & change its content, and even alter its structure and style! This all happens by making use of your browser’s document object model (more on that later). As you’ll see, this is the best way to communicate with your user. But, using the document object model requires knowledge of how your page is structured and of the programming interface that is used to read and write to the page. We’ll be getting there soon enough. But first, we’ve got some more JavaScript to learn.
This is what we’re working towards. When you get there you’ll be able to read, alter and manipulate your page in any number of ways.
Let’s take a closer look at how console.log
works so we can use it in this chapter to see the output from our code, and throughout the book to inspect the output of our code and debug it. Remember though, the console is not a browser feature most casual users of the web will encounter, so you won’t want to use it in the final version of your web page. Writing to the console log is typically done to troubleshoot as you develop your page. That said, it’s a great way to see what your code is doing while you’re learning the basics of JavaScript. Here’s how it works:
Every browser has a slightly different implementation of the console. And, to make things even more complicated, the way that browsers implement the console changes fairly frequently—not in a huge way, but enough so that by the time you read this, your browser’s console might look a bit different from what we’re showing here.
So, we’re going to show you how to access the console in the Chrome browser (version 120) on the Mac, and we’ll put instructions on how to access the console in all the major browsers online at http://wickedlysmart.com/hfjsconsole. Once you get the hang of the console in one browser, it’s fairly easy to figure out how to use it in other browsers too, and we encourage you to try using the console in at least two browsers so you’re familiar with them.
Note: You don’t need to type the Howdy code in. We’re just learning where the console is. We’ll start typing in code in just a sec...
Let’s put all these new JavaScript skills and console.log
to good use with something practical. We need some variables, a while
statement, some if
statements with else
s. Add a little more polish and we’ll have a super-serious business application before you know it. But, before you look at the code, think to yourself how you’d code that classic favorite, “99 bottles of rootbeer.”
const word = "bottles"; let count = 99; while (count > 0) { console.log(count + " " + word + " of rootbeer on the wall"); console.log(count + " " + word + " of rootbeer,"); console.log("Take one down, pass it around,"); count = count - 1; if (count > 0) { console.log(count + " " + word + " of rootbeer on the wall."); } else { console.log("No more " + word + " of rootbeer on the wall."); } }
Good point! Yes, it’s time. Before we got there we wanted to make sure you had enough JavaScript under your belt to make it interesting. That said, you already saw in the beginning of this chapter that you add JavaScript to your HTML just like you add CSS; that is, you just add it inline with the appropriate <script>
tags around it.
Now, like CSS, you can also place your JavaScript in files that are external to your HTML.
Let’s first get this serious business application into a page, and then after we’ve thoroughly tested it, we’ll move the JavaScript out to an external file.
You already know you can add the <script>
element with your JavaScript code to the <head>
or <body>
of your page, but there are a couple of other ways to add your code to a page. Let’s check out all the places you can put JavaScript (and why you might want to put it one place over another):
Going separate ways hurts, but we know we have to do it. It’s time to take your JavaScript and move it into its own file. Here’s how you do that...
Time to stretch your dendrites with a puzzle to help it all sink in.
ACROSS
1. Variables are used to store these.
4. Use _____________ to troubleshoot your code.
7. Today’s JavaScript runs a lot ________________ than it used to.
8. There are 99 _____________ of rootbeer on the wall.
9. To link to an external JavaScript file from HTML, you need the _______ attribute for your <script> element.
10. Each time through a loop, we evaluate a ______________ expression.
13. The if/else statement is used to make a ____________.
14. All JavaScript statements end with a ___________.
16. You put your JavaScript inside a ______________ element.
DOWN
2. You can concatenate _______________ together with the + operator.
3. Store values that don’t change in this.
5. 3 + 4 is an example of an _____________.
6. JavaScript adds _______________ to your web pages.
9. Each line of JavaScript code is called a _______________.
10. To avoid embarrassing naming mistakes, use __________ case.
11. Do things more than once in a JavaScript program with the _________ loop.
12. JavaScript variable names are _________ sensitive.
15. To declare a variable, use this keyword.