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âre going to 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 (and most ancient) browsers; JavaScriptâs even branching out and being embedded in a lot of environments outside 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 to add a little behavior as well? These days, thereâs no need for the page to just sit there. Great pages should be dynamic, interactive, and they should work with your users in new ways. 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 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.
Relax
Just relax. At this point we donât expect you to read JavaScript like you grew up with it. In fact, all we want you to do right now is get a feel for what JavaScript looks like.
That said, youâre not totally off the hook because we need to get your brain revved up and working. Remember that code on the previous page? Letâs just walk through it to get a feel for what it might do:
JavaScript 1.0 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. And towards 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 their own 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? They created their own scripting language soon after Netscape did, named, um, JScript, and it was, um, quite similar to JavaScript. And so began the browser wars. |
Between 1996 and 2000, JavaScript grew up. In fact, Netscape submitted JavaScript for standardization and ECMAScript was born. Never heard of ECMAScript? Thatâs okay, now you have; just know that ECMAScript serves as the standard language definition for all JavaScript implementations (in and out of the browser). During this time developers continued struggling with JavaScript as casualties of the browser wars (because of all the differences in browsers), although the use of JavaScript became common-place in any case. And while subtle differences between JavaScript and JScript continued to give developers headaches, the two languages began to look more and more like each other over time. JavaScript still hadnât outgrown its reputation as an amateurish language, but that was soon to change... |
Finally, JavaScript comes of age and gains the respect of professional developers! While you might say itâs all due to having a solid standard, like ECMAScript 5, which is now implemented in all modern browsers, itâs really Google that pushed JavaScript usage into the professional limelight, when in 2005 they released Google Maps and showed the world what could really be done with JavaScript to create dynamic web pages. With all the new attention, many of the best programming language minds focused on improving JavaScriptâs interpreters and made vast improvements to its runtime performance. Today, JavaScript stands with only a few changes from the early days, and despite its rushed birth into the world, is showing itself to be a powerful and expressive language. |
1995 | 2000 | 2012 |
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. 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, âSure, I 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 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 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 up 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:
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 var 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 | delete | for | let | super | void |
case | do | function | new | switch | while |
catch | else | if | package | this | with |
class | enum | implements | private | throw | yield |
const | export | import | protected | true | Â |
continue | extends | in | public | try | Â |
debugger | false | instanceof | return | typeof | Â |
default | finally | interface | static | var | Â |
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!
while (juggling) { keepBallsInAir(); }
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.
var scoops = 5; while (scoops > 0) { document.write("Another scoop!<br>"); scoops = scoops - 1; } document.write("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! <br>â to the 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.
var scoops = 5; while (scoops > 0) { document.write("Another scoop!<br>"); scoops = scoops - 1; } document.write("Life without ice cream isn't the same");
And continues...
var scoops = 5; while (scoops > 0) { document.write("Another scoop!<br>"); scoops = scoops - 1; } document.write("Life without ice cream isn't the same");
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!
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.
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.
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.
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 25) 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.
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 beer.â
var word = "bottles"; var count = 99; while (count > 0) { console.log(count + " " + word + " of beer on the wall"); console.log(count + " " + word + " of beer,"); console.log("Take one down, pass it around,"); count = count - 1; if (count > 0) { console.log(count + " " + word + " of beer on the wall."); } else { console.log("No more " + word + " of beer on the wall."); } }
Brain Power
Thereâs still a little flaw in our code. It runs correctly, but the output isnât 100% perfect. See if you can find the flaw, and fix it.
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...
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â.
Now we 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 a src=âcode.jsâ, weâre assuming that the code file is in the same directory as the HTML file.
Get Head First JavaScript Programming 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.