Chapter 1. A Quick dip into javascript: Getting your feet wet
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 into those 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!
The way JavaScript works
If you’re used to creating structure, content, layout, and style in your web pages, isn’t it time you added a little behavior as well? After all, there’s no need for the page to just sit there. Great pages should be interactive and dynamic. That’s where JavaScript comes in. Let’s start by taking a look at how JavaScript fits into the web page ecosystem:
How you’re going to write JavaScript
JavaScript is the programming language for the web browser. With your typical programming language, you have to write the code, compile it, link it, and deploy it. With JavaScript, all you need to do is write code 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:
Writing
You create your page just like you always do, with HTML content and CSS styles. And you also include JavaScript in your page. As you’ll see, just like with HTML and CSS, you can put everything together in one file, or you can place the JavaScript in its own file, to be included in your page.
Note
We’ll talk about the best way in a bit.
Loading
Point your browser to your page, just as you always do. The browser sees the code and begins parsing it immediately, getting ready to execute it. Note that like with HTML and CSS, if the browser sees errors in your code, it will do its best to keep moving and reading more JavaScript, HTML, and CSS. The last thing it wants to do is not be able to give the user a page to see.
Executing
The browser starts executing your code as soon as it encounters the code in your page, and continues executing it for the lifetime of your page. Some code executes once and is not executed again (until you reload the page); other code is executed whenever the user does something, like click a button or move the mouse. You’ll see examples of both in this book.
How to get JavaScript into your page
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. 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.
A little test drive
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.
JavaScript, you’ve come a long way...
Netscape might have been before your time, but it was the first real browser company. Back in the mid-1990s browser competition was fierce, particularly with Microsoft, and so adding new, exciting features to the browser was a priority.
Toward that goal, Netscape wanted to create a scripting language that would allow anyone to add scripts to their pages. Enter LiveScript, a language developed in short order to meet that need. Now, if you’ve never heard of LiveScript, that’s because this was all about the time that Sun Microsystems introduced Java, and as a result drove its stock to stratospheric levels. So, why not capitalize on that success and rename LiveScript to JavaScript? After all, who cares if they don’t actually have anything to do with each other? Right?
Did we mention Microsoft? It created its own scripting language soon after Netscape did, named, um, JScript, and it was, um, quite similar to JavaScript. And so began the browser wars and a frustrating time for developers.
JavaScript 2015
After all that confusion, JavaScript finally grew up. ECMAScript, an official language definition for JavaScript was born, and now serves as the standard language definition for all JavaScript implementations (in and out of the browser).
By 2015, JavaScript had finally come of age and gained the respect of professional developers. Having a solid standard helped, along with serious commitment from browser makers like Google, which pushed JavaScript into the professional limelight with Google Maps and other complex browser-based applications.
With all the new attention, many of the best programming language minds focused on improving JavaScript’s interpreters and made improvements to its runtime performance. After JavaScript 2015, a major language update, we switched from official version numbers for language releases to yearly updates.
JavaScript 2024
Today, JavaScript is the language of the web. Pre-compilers make interpreting JavaScript code in webpages blindingly fast. Syntax checkers, syntax-aware code editors, and robust browser-based debugging tools have professionalized web development. JavaScript is one of the most popular languages in the world and has been implemented in environments as diverse as embedded systems, web servers, and music-making applications.
The language is fairly mature at this point. Most language updates are small and incorporated quickly into browsers. Numerous JavaScript libraries and frameworks mean that you can do almost anything with JavaScript that you can do in any other language.
After a strange and contentious history, JavaScript has made it!
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.
Note
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 and CSS to date, you should know that there is something fundamentally different about learning a programming language.
With HTML and 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 “calculate the user’s score by summing up all the correct answers” or “do this action 10 times” or “when the user clicks on that button play the you-have-won sound” or even “go off and get the current temperature, 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...
How to make a statement
When you create HTML, you usually mark up text to give it structure. To do that, you add elements, attributes, and values to the text:
<h1 class="drink">Mocha Caffe Latte</h1> <p>Espresso, steamed milk, and chocolate syrup, just the way you like it.</p>
Note
We’re using HTML to mark up text to create structures like headings and paragraphs. Like, “I need a large heading called Mocha Caffe Latte; it’s a heading for a drink. And I need a paragraph after that.”
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 a page:
Variables and values
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 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:
Constants, another kind of variable
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
and 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 earthRadius
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 earthRadius
never changes? We can use a constant instead of a variable, like this:
Back away from that keyboard!
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 variable names with a letter or an underscore.
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 later in 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
Express yourself
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:
Expressions can evaluate to a few other types, too; 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!
Doing things more than once
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, for of, 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:
How the while loop works
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:
let scoops = 5;
while (scoops > 0) {
console.log("Another scoop!");
scoops = scoops - 1;
}
console.log("Life without ice cream isn’t the same");
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!” to the browser’s console:*
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 three. But that’s still more than zero:
Once again, we write the string “Another scoop!” 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!” 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:
let scoops = 5; while (scoops > 0) { console.log("Another scoop!<br>"); scoops = scoops - 1; } console.log("Life without ice cream isn't the same");
And continues...
let scoops = 5; while (scoops > 0) { console.log("Another scoop!"); scoops = scoops - 1; } console.log("Life without ice cream isn't the same");
Until the last time...this time, something’s different. Scoops is zero, 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 console.log and write the string “Life without ice cream isn’t the same”. We’re done!
Making decisions with JavaScript
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 the code inside its curly braces (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:
Reach out and communicate with your user
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 a couple of them. Let’s get a quick overview and then we’ll dive into these in more detail throughout the book:
Create an alert.
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.
Note
We’re using these two methods in this chapter.
Write directly into your document.
Think of your web page as a document (that’s what the browser calls it). You can use a function called 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 in old code.
Use the console.
Every JavaScript environment also has a console that can log messages from your code. We’ve been using this in our examples so far. 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 the console log in just a moment). You can view console.log
as a great tool to get started with JavaScript and 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.
Note
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.
Directly manipulate your document.
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 and change its content, and even alter its structure and style! This all happens by making use of your browser’s document object model. As you’ll see, this is the best way to communicate with your users. 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.
Note
This is what we’re working toward. When you get there, you’ll be able to read, alter, and manipulate your pages in any number of ways.
A closer look at console.log
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:
Opening the console
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.
We’re going to show you how to access the console in the Chrome browser (version 123) on macOS, and we’ll put instructions on how to access the console in all the major browsers online at https://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
Note: you don’t need to type the Howdy code in. We’re just showing where the console is. We’ll start typing in code in just a sec...
Coding a Serious JavaScript Application
Let’s put all these new JavaScript skills and console.log
to good use with something practical. We need some variables, a while
statement, and 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 at 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.
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.
How do I add code to my page? (let me count the ways!)
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):
We’re going to have to separate you two
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...
Open “index.html” and select all the code; that is, everything between the <script> tags. Your selection should look like this:
Now create a new file named “code.js” in your editor, and place the code into it. Then save “code.js” in the same folder as your HTML.
You need to place a reference to the “code.js” file in “index.html” so that it’s retrieved and loaded when the page loads. To do that, delete the JavaScript code from “index.html”, but leave the <script> tags. Then add a src attribute to your opening <script> tag to reference “code.js”.
That’s it, the surgery is complete. Now you need to test it. Reload your “index.html” page, and you should see exactly the same result as before. Note that by using src=“code.js”, we’re assuming that the code file is in the same directory as the HTML file.
Get Head First JavaScript Programming, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.