JavaScript for Designers | A Morning Jolt of JavaScript
Course Developer: Geoph Essex
Instructor: Geoph Essex
Layout: Geoph Essex, Patricio Sarzosa
Editor: Gordon Drummond, Mark Waters
Geoph Essex
Hi there—I'm Geoph, and I've spent decades programming and designing games, apps, and Web sites. For designers coming into our brave new technological world from a strictly creative or artistic view, JavaScript might seem a little daunting! This course is about getting you comfortable using JavaScript, adding rich interfaces and exciting interactivity to Web sites without getting swamped with technical details.
A Morning Jolt of JavaScript
Good morning! Nothing gets your Web design started like a little jolt of JavaScript.
It's hard to find a major Web site these days that doesn't use JavaScript. If HTML is the bare bones of a Web site that provides structure, and CSS is the skin covering that HTML skeleton to make it look good, then JavaScript is the muscle—giving our site a chance to really flex and move around.
JavaScript gives us that dynamic and, more importantly, immediate feel we expect from the modern Web, creating user-friendly interfaces and interactivity for our Web sites. It lets us animate, change, and update a Web page in response to each visitor's actions or preferences. We can enhance usability, implement responsive design, and make Web pages fun and engaging.
In this course, you'll learn the fundamentals of JavaScript programming—but as a designer, you'll focus on how you can add interactivity and responsiveness to your Web designs without too much technical jargon or coding mumbo jumbo. Once you've got the basics down we'll concentrate on freely available frameworks like jQuery and Bootstrap—powerful, designer-friendly toolkits that give us an easy, efficient way to make our Web sites do what we want them to do.
Your goal here is to learn the JavaScript you'll need to know in order to work with those toolkits—just enough programming to give you an edge, but not so much as to overwhelm you.
In this first lecture, we're going to dive head first into a JavaScript "crash course." It may seem like a lot at first, but we're purposely covering a lot of ground, so stick with it—you'll soon see how it all fits together to give you just what you need to move forward to the next level.
In this lecture, you can expect to:
Set up a basic JavaScript skeleton within an HTML document. Learn how to write fundamental JavaScript expressions and statements. Learn how to define and use variables, operators, and functions. Discover how variable types work in JavaScript. Learn how to construct and understand conditional statements.
JavaScript and Java are two different programming languages, even though they have similar names.
"Script" and "program" can be used interchangeably; they mean pretty much the same thing.
Client-side programs run in your browser. Server-side programs run on a host machine that sends data to your browser.
In Web development, different tools and techniques are usually different rather than "better." Each has pros and cons.
Never use a word processing program to write code!
JavaScript is added to an HTML page by using <script> tags.
Link to an external .js file if you plan to use your script on more than one page.
Don't put any HTML or CSS in a .js file!
"Deprecated" code is code that we no longer use.
JavaScript isn't math or science—it's just another language.
JavaScript programs are comprised of statements.
Expressions are evaluated: turned into values that JavaScript can remember, change, and compare.
Think of variables as "boxes" that you can keep your data in.
JavaScript is a cAsE sEnSiTiVe language! Uppercase and lowercase letters are not the same in keywords and names.
Operators are used to assign, alter, and compare values.
Expressions may be evaluated incorrectly if you don't remember the order of operations!
Avoid writing the same set of code more than once—use a function instead.
Functions use temporary names for the values you send them, and won't directly alter the values of the original variables you sent.
Even once it's defined, a function will not run until you call it!
JavaScript data types include numbers, strings, and Boolean values.
Always enclose your strings in matching "quote" marks!
You can use a \backslash to "escape" quote marks you need to put inside a string.
"Concatenation" means adding two strings together. In JavaScript, you can do this with the + operator.
Strings are cAsE sEnSiTiVe too!
The Boolean values of "true" and "false" are the backbone of all logic and programming.
Conditional "if" statements check if expressions are true or false, and proceed accordingly.
Don't confuse the single = for assignments with the double == for comparisons!
An "if-else" gives JavaScript an alternative course of action in case an expression turns out to be false.
What is JavaScript?
JavaScript is a programming language that you add to Web pages. It gives you control over the appearance of your page, its content, and its behavior when a user interacts with it. You can see JavaScript in action when you're checking your webmail, putting your information into a form, exploring Google Maps, or watching your feed go by on Facebook. These days, JavaScript is as ubiquitous as HTML and CSS on the World Wide Web—it's hard to imagine any serious professional or commercial site that wouldn't use all three.
You may have heard of another programming language called Java—but don't confuse JavaScript with Java, especially during a job interview! They've got similarities, but they're two separate languages. JavaScript was originally called "LiveScript" when it was developed by Brendan Eich (back in 1995) for Netscape, one of the earliest companies to dominate the Web browser market. Who? It's okay if you haven't heard of them—they're not as well-known these days. The company was bought by AOL in 1999, but their contributions to Web technology still thrive in the form of JavaScript and the Netscape Navigator browser's spiritual successor, Firefox.
Navigating from past to present... Netscape originated both JavaScript and SSL (the Secure Sockets Layer security protocol), cornerstones of the Web as we know it. They also released the source code for the Navigator browser, which was then rewritten using the Gecko rendering engine—the engine behind a number of popular browsers since, including Mozilla Firefox.
Brendan initially developed the language in a mere 10 days. (Don't worry—you won't be expected to replicate that feat here!). Since Netscape had also incorporated the very popular Java technology in their latest browser, they decided to call their new, more accessible programming language "JavaScript"—which, in the long run, is probably a lot more confusing than it needed to be! (Officially, JavaScript is a dialect of a language called ECMA-262, the standard version of a scripting language called ECMAScript.)
JavaScript is a client-side, object-oriented programming language. Let's explore what that means.
Object-Oriented Programming
Object-oriented programming is a programming model in which everything you work with is an object. This is a very strong, flexible paradigm that means a lot to professional programmers—it's the principle behind all of the most powerful programming languages in use today.
Objects are pieces of data, but they can literally be any sort of data: a method for doing something like calculating tax or alphabetizing names; a piece of information like a password or a list of ingredients (with each ingredient being an object, too!); even a more intrinsic form of data like the definition of one of those methods or pieces of information. Being able to work with all of these things in the same basic way—as objects—allows coders to do some very nifty things.
If the nature (or point) of object-oriented programming doesn't yet seem clear to you, that's not a problem—you'll see it in action in this course, and we'll explore how the kind of programming we'll be doing is object-oriented.
Client-Side vs. Server-Side
When it comes to the Web, a client is the browser on your computer—your local system—which requests and receives data from a server somewhere on the Internet (a remote system). There are advantages and disadvantages to running your programs either client-side (on your computer) or server-side (on a machine somewhere else, where the Web site you're looking at is actually stored).
If you've got a lot of number-crunching to do, or some heavy data to keep track of, server-side technology (like PHP, ASP.NET, or Ruby on Rails) is an ideal choice. You can't count on every user having an über-powerful computer system that can take care of all the heavy lifting itself. You'll also require server-side programs when you need to send or retrieve data—whether you're giving your user a list of available merchandise, storing their contact or billing information, or processing payments. Of course, everything that you do server-side needs to eventually be sent through the Internet connection to or from a user's browser...which can take time. Even a few extra seconds can make a big difference for some Web sites or applications.
Who ya gonna call? The Internet Movie Database (IMDb) relies on supplying the user with lots of information stored on their servers about movies, actors, filmmakers, and more. Since all that information needs to be kept and retrieved as needed, it involves a lot of server-side technology. (But don't forget that a lot of the interactivity is built on client-side technology!).
Meanwhile, the big advantage of client-side programming is immediacy—it happens right then, right on the user's computer, with little to no delay between the user's actions and the Web page's response. Click an image and it zooms in instantly. Click "Submit" and find out if you accidentally missed a required bit of information. This means we can make Web pages truly interactive, practically indistinguishable from a program right on the user's desktop! Sites like Google Maps and Amazon take this about as far as you can go with it, but even simpler JavaScript can really add a lot of bells and whistles to the user experience.
I can see my house from here! It's no surprise that millions use Google Maps to find what they're looking for almost anywhere on Earth. This extraordinary real-time navigation is made possible through the use of some seriously polished client-side technology, creating a fun and engaging interactive experience. (But don't forget that it's the server-side technology which supplies all the maps and labels we watch scrolling by!).
Since it's a client-side programming language, any JavaScript program that you write is downloaded from the (remote) server and then run within the user's Web browser, the (local) client. There are other client-side technologies that you'll encounter, including one you've almost certainly heard of: Adobe Flash (once upon a time, it was Macromedia Flash). Flash has a long history of providing more powerful animation and interactive capabilities than traditional Web pages could manage, but unfortunate security holes, frequent bugs in the player, and conflicts with other companies kept Flash out of the mobile market...which nearly killed it. In a bold move, Adobe transformed Flash into a new application called Animate. Animate aims to be an authoring environment for rich Web applications just like those JavaScript can create. It will still work on the same basis as Flash, but will no longer be limited to creating Flash movies—in other words, it will actually be a competitor to JavaScript and its allied technologies.
Flash likely won't disappear, but it does need to adapt quickly, because the new paradigms based on heavy use of JavaScript are paving the way toward the future on all devices. Sometimes it can be tricky to tell the difference between a Flash movie and a page that's been built with intricate JavaScript—they often look and feel quite similar. To tell if a particular Web site feature is delivered with Flash, you can right-click (Control-click on a Mac) that feature; if you see a context menu pop up with words like "About Adobe Flash Player," then you know you're looking at Flash.
So in terms of actually making stuff, is Flash better, or is ultra-modern HTML5—a powerful team comprised of JavaScript, CSS, and modern HTML—better? As with most such questions, it's a red herring: neither is better, but both are tools that excel in certain respects and fall short in other respects. Each has its strengths and advantages, and skilled designers and developers never turn their noses up at any useful tool.
No holds barred! The developers behind Flash vs. HTML5 started out wondering if there would be any major differences between making a game in Flash and making that same game in HTML5...so they did both! Then they analyzed what the differences were, in the game itself, and in how they could offer it to consumers. If you've been reading this lesson closely, their conclusions won't surprise you.
Just like the choice between Flash and JavaScript, the "choice" between client-side and server-side applications is a kind of silly question. Most modern Web design is rapidly closing the gap, as nearly all major Web services have a need to incorporate both these days. JavaScript itself, though a client-side technology, is finding use on the server side of things in the form of Node.js—a bit of server-side technology that can be written using JavaScript, just like the stuff you'll learn in this course! The real takeaway here is that neither client-side nor server-side is "better." They rely on each other to bring us all full-featured, good-looking, powerful Web applications. But as a designer, you'll work mostly on front-end design, which means client-side stuff—and that means starting from square one.
A JavaScript Primer (See JavaScript. See JavaScript Run.)
JavaScript can be embedded—written right into an HTML file—or kept in an external file containing just the JavaScript, which we can then link to from one or more Web pages. In this way, it's just like a CSS style sheet! If you're not going to use the same program in more than one page, it's fine (and a little quicker and easier) to simply embed it in your HTML.
There are generally two places where embedded JavaScript can go: in the <head> of your HTML, between the opening tag and the closing </head> tag (usually right before the closing tag); or in the <body> of your HTML, anywhere between its opening and the closing </body> tag. While you can put JavaScript elsewhere in your HTML page, and it may work just fine, that's not considered valid, and will give you warnings or errors if you try to validate your HTML code.
A nice place for some JavaScript. Make sure you know where to put your JavaScript code when you embed it in HTML code—in the head, or in the body.
By the way: if you see me refer to "code" instead of "programming," don't be worried about yet another term to memorize! Code is just more general terminology. For instance, HTML is a coding language, but it is not a programming language—it's what we call a mark-up language, which typically offers structure but not instructions to a computer. JavaScript is a coding language, and is also a programming language, since it provides direct, explicit instructions. (The border is a little fuzzy, and is getting even fuzzier as time goes by, but this is a good foundation for a general understanding of the difference.)
Breaking the code. While HTML and JavaScript are both code, HTML is a mark-up language, while JavaScript is a programming language. XML, like HTML, is mark-up; PHP, like JavaScript, is programming (though PHP is server-side!). CSS is a style language, telling the computer how to present information visually (or otherwise—audio CSS exists!). All code is data, but not all data is code—plain text files, for example, are just data with no specified structure, formatting, or instructions...no code!
So JavaScript gives the browser instructions, which you write out as a program. Whenever you want to embed your program in an HTML page, you can do it the same way you do nearly anything in HTML: you add HTML tags! In this case, you need the opening <script> and closing </script> tags, like this:
<script type="text/javascript">
</script>
That first HTML tag tells the browser: "Okay, here we've got some JavaScript instead of HTML." Then the closing tag tells it: "All done with the JavaScript—now we're back to HTML!" It's just like a <p> tag—the opener tells the browser you've got a paragraph coming up next, and the closer tells it the paragraph is finished. Easy!
The stuff between your opening and closing script tags is the actual script in your little JavaScript sandwich. For example, to make a dialog box pop up to greet the world, you would add this to your page:
"Hello, programmer!" - the World. A basic JavaScript-generated message (in Mozilla Firefox).
Using the Right Text Editor (Not Bringing a Knife to a Gunfight—or Vice Versa!)
Throughout this course, I'm going to strongly suggest that you use a text editor to do your code work. Some of you may be familiar with WYSIWYG (What You See is What You Get) authoring environments like Adobe Dreamweaver (also originally from Macromedia, just like Flash!), but my recommendation and request is that you avoid the temptation to use them. Why? For two important reasons, really:
1. It's much better practice to get the hang of doing all of this yourself, instead of letting a WYSIWYG app do it for you. It'd be hard to learn to ride a bicycle if somebody else was always pedaling for you, right?
2. As popular as they are, WYSIWYG apps do not produce good, clean, and efficient code. In fact, as any experienced designer or developer will tell you, they create a giant mess of code (commonly referred to as spaghetti code because of the tangled nonsense!) that is very hard to read, and even harder to correct (if anything goes wrong).
So to keep everything legible and correct, and to make sure you learn what you need to know, we're going to hand-code everything instead of using an app that does the work for us. There are a lot of excellent, highly useful text editors out there. You can stick with the simple text editor that comes with your computer, like Notepad for Windows or TextEdit for Mac (though make sure TextEdit isn't in word processing mode!). You could spend some money on something a little spiffier, like BBEdit, TextWrangler, or Sublime. Or you could get a text editor like Notepad++, which is feature-rich and easy to use...not to mention free! (Notepad++ is, in fact, what I use for most of my own coding work, and you'll see it in action in the screen captures throughout this course.)
Whatever you do, though, do not try to write code in a word processor—like Microsoft Word, for example. Word processing applications add in a lot of code "behind the scenes" that can interfere with the code you're trying to write.
Take Note! This is Notepad++, a free text editor with all the features you might need for robust, efficient coding in a variety of languages (like JavaScript, HTML, and CSS). You can download it right from its developer at notepad-plus-plus.org.
Now that you're armed (and dangerous) with your favorite text editor, let's jump right in and give this a try! Open your text editor and create a new document. Let's start with the basic structure of an HTML page. Since you should already have taken some HTML (and CSS!) courses, this should be pretty familiar to you. Type this into your new document:
Now go ahead and add our simple JavaScript in. You could put it inside the head, just before the closing </head> tag, or in the body, between the <body> and </body> tags. Don't forget to include your opening <script> tag and your closing </script> tag! (Note that the highlighted parts below are the only lines I've added.)
Save this file with a name like hello_world.html. Make sure to use an html extension, not a txt extension (it's okay if your text editor doesn't specify the type right away, the extension will be enough for the browser to understand!). Open the HTML file in your browser, and you should see something very much like the example I showed you earlier: a pop-up dialog declaring a greeting to the world. If you don't get that result, compare your page with the example1_hello_world.html file accompanying this lecture. (Remember that all the files for the course are located in the course downloads area.)
As you'll quickly learn, even just one minor typo can kill a JavaScript program, so make sure you type the sample code exactly as written above—even changing lowercase letters to capital or vice versa can completely break your code! (You'll learn some techniques later in the course for finding and fixing JavaScript errors.) Most importantly, be sure to type the script rather than just copying and pasting it. Copy/pasted script may not work quite right...and it certainly won't teach you how to write your own JavaScript.
JavaScript from an External File (The Calls are Coming from Outside the House)
If you plan on writing JavaScript code that will be used on more than one Web page (for example, a script for adding rollover image functionality to every page on a Web site), it's more efficient to put your JavaScript into an external file and link to it on every page that uses the same code. That way, you only have to write the code once—keep that in mind, because it's a mantra that dictates a lot of our best practices when we're writing JavaScript.
Keep the utilities running...Using an external JavaScript file linked to each of your HTML pages is like having the power company provide electricity for your whole neighborhood. Nobody has to have their own generator: the power (code!) is distributed to every house (page!) that has a power line (link to the JavaScript!).
Here are a couple of guidelines to remember when you're creating a separate JavaScript file:
JavaScript files end with a .js extension. For example, scripts.js is a valid JavaScript file name.
JavaScript files should contain only JavaScript code. Don't put any lines of CSS or HTML in a JavaScript file, not even the <script> tags (after all, those tags are HTML, not JavaScript!).
To use the code from an external script in any individual Web page, you still use the <script> tags, with a slight difference. As an example, if your JavaScript file is named scripts.js, you can link to it like this:
There are some important rules for using the tag this way:
Like embedded JavaScript, you should generally put the linking <script> tag for an external .js file before the closing </head> tag of your page, and also put it before any other scripts (external or embedded) that might need to use some of the code from this script. (Order matters! If you tried to eat a cheeseburger before you ordered it, you'd chomp down on empty air, right?)
The src attribute is just the path to where the JavaScript file is on your site. It works just like the src attribute for an image or the href attribute for a hyperlink or style sheet. In the above example, you're telling the Web browser to look for a file named scripts.js located in the same folder as the Web page itself.
Don't put any JavaScript code between your <script> tags when linking to an external JavaScript file! Web browsers ignore anything inside a <script> tag when its src attribute is included.
When it comes to that third rule, though, don't forget that it is possible (and common!) to include more than one set of <script> tags per page. You can link to multiple external JavaScript files, or link to an external file and include an embedded JavaScript program on the page itself, or include multiple embedded programs—or any combination of these, really. For example, the following is perfectly valid:
The first <script> tags above tell the Web browser to download an external JavaScript file (and to run any code inside that file!), while the second set of tags runs the embedded JavaScript program written right there in the HTML page.
Now that you've got an understanding of how to use external JavaScript files, let's try it out—it's a technique you'll make use of very often as a designer! Try the following walkthrough, step by step:
1. Save a copy of the hello_world.html file you created earlier (or whatever you chose to call it!). You can name this copy something like hello_external.html.
2. Create a new, blank document in your text editor and save it as hello_world.js. Save it in the same folder as the HTML file.
3. Cut (remember, a cut copies and deletes simultaneously) the JavaScript out of your new HTML page—just the JavaScript, not the <script> tags! Then paste that code into your new .js file.
4. Change the <script> tag in the new HTML file to link to your hello_world.js file. (If you need help, look above at the examples of including external JavaScript files in your page, and make sure you use the right file name.)
5. Save both files (hello_external.html and hello_world.js) and load the HTML page into your Web browser.
Assuming everything went smoothly, you should see the same pop-up dialog as you did before, when we embedded the program (instead of externally linking it). If it isn't working, take a look at example2_hello_world.js and example2_hello_external.html in the files for this lecture. Also, make sure you're using the correct path to your hello_world.js file. If you saved it to a different folder than your HTML file, you'll need to account for that in your src path.
Deprecated Code (Yesterday's News)
It's possible that as you study JavaScript, and find examples online to help you learn more, you'll see code that has some additional elements to it. Stuff like this:
// ******** An example of what NOT to do!! ********
<script type="text/javascript" language="JavaScript">
<!--
alert("Hello world!");
//-->
</script>
The above snippet has some highlighted examples of deprecated code in it. Deprecated code is stuff we used to put into our code, for one reason or another, but we don't have to anymore and therefore should not. The folks who keep coding languages up to date and running smoothly keep tabs on stuff like this, and let us know when bits of code that we habitually use become deprecated. Once they do, developers ideally toss them out and no longer use them, so as not to confuse the issue or run into future problems.
Above, you'll note the language attribute—now deprecated in <script> tags, since browsers can safely assume that any script will be JavaScript (so we don't need to specify!). Oddly enough, you could even omit the type attribute and most browsers will deal with it just fine; but since that attribute is still part of the standards (it's not deprecated), don't throw it out with the trash. You should keep including it in your work for the foreseeable future.
Those other two lines of strange punctuation you might recognize as HTML comments. Older browsers that didn't recognize <script> tags would just display any code inside them like plain old text written in an HTML page, for all the world's users to see—definitely not the right idea! To avoid that, developers would hide the code inside HTML comments, which newer browsers would know to ignore when reading JavaScript. These days, there aren't really any browsers left that don't know what to do with a <script> tag, so the HTML comment trick is unnecessary. Also, those HTML comment tags can actually interfere with writing some otherwise valid JavaScript programs. For both reasons, the practice is no longer used...and therefore deprecated code.
Though you shouldn't use any deprecated code in your work, I'm pointing these out so you're aware of them. Whenever you copy code from interesting sites to learn how it works—a practice I happily encourage you to try frequently!—you might see deprecated code like this. Now you know that you can safely take out the HTML comment tags (<!-- and //--> —the second one also includes a JavaScript comment mark at the beginning) and the language attribute without worrying about it.
JavaScript Building Blocks (The A, B, Cs of JS)
A lot of folks—designers included—might nervously look at programming as a math-heavy, very technical science. The trick lies in understanding how false that perception is!
Like any programming language, JavaScript is a language. That's why we call them languages! And learning how to write (and read) a programming language is much more like learning Spanish, Russian, Chinese, English—or any of the things you already think of as languages—and much less like learning math or science. Math and science can come into play if you're creating a program that needs them—you might need some strong math skills to make an accounting program, or some in-depth scientific knowledge to make a physics engine for a game, but that's just the same as saying you'd need to understand how taxes work to make a program that does your returns for you. Knowledge of a specific subject is separate from knowing a language—you'll find it hard to discuss it if you don't know the subject, but you can certainly discuss other subjects as long as you speak the language.
So just to learn how to program, rather than how to program a specific application? All you need to learn is the logic of these very simple creatures we call computers (which are nowhere near as complex as people!), and how to speak their language. And as with any language, there's a lot of vocabulary, some spelling rules, a bit of grammar and syntax, and a smattering of punctuation that you'll need to get straight. In this lecture, we'll cover some of the most fundamental parts of JavaScript; you'll learn more building blocks as you continue through the course.
Polyglots of the world, unite! Whether in Spanish, Russian, Chinese, JavaScript, English, or any other language, to walk the walk, all you need to do is talk the talk.
Statements (Your Wish is JavaScript's Command)
In English, we have sentences—made up of one or more words, a single sentence conveys a single, specific idea. When you want to talk about more than one thing, you use multiple sentences. (Otherwise, your sixth-grade English teacher will reprimand you for writing a run-on sentence!).
In JavaScript, a sentence is known as a statement. It represents a single idea or action in your scripted "conversation" with JavaScript. For example, in the script you created earlier you wrote the following statement:
alert("Hello world!");
This single action—a JavaScript statement—opens a dialog box with a message. You create your script by putting together line after line of statements, each of which does something that typically builds on the statements that came before it.
In its most basic format, a statement is a single line of code that ends in a semi-colon (like the example above). The semi-colon in JavaScript is like a period at the end of a sentence in English—it tells the browser when the statements ends. Most of the statements you write will be like this.
Don't forget the semi-colon at the end of single-line statements, because that's an error that can prevent your script from working correctly! As you'll see in just a bit, sometimes JavaScript is organized into more complex statements, spanning multiple lines. You can think of these as the JavaScript equivalent of "paragraphs," discussing several thoughts about the same subject. But whenever you have a single-line statement, make sure you end it with a semi-colon.
Expressions (Like My Motherboard Used to Say...)
If statements are sentences, then expressions are the JavaScript words that make up those sentences. Like words are made up of letters or parts of other words, expressions are made up of all sorts of values, references to those values, and even other expressions, which JavaScript evaluates (on the fly) to determine what you mean by that expression.
The following are all valid JavaScript expressions:
You may have noticed the parentheses in that last example. The expressions in any programming language are evaluated based on the rules of that language, which—for numbers especially—often follow the standard order of operations in mathematics. (In case you don't know, that order is PEMDAS: parentheses, exponents, multiplication and division, addition and subtraction.)
In the last two examples above, the parentheses remind JavaScript to consider things in a different order: 7+3*8 means "seven plus the result of three times eight," because multiplication comes before addition in the order they're evaluated. Since parentheses come first: (7+3)*8 means "the result of seven plus three, times eight." It's a subtle difference, but it matters:
7+3*8 // This is 7, plus 3*8: 7 plus 24, or 31
(7+3)*8 // this is 7+3, times 8: 10 times 8, or 80
Note that I haven't put semi-colons at the ends of these, because they're examples of expressions, not statements. Alone, they wouldn't do a whole lot! It's when you start working with them all together that the magic happens.
Variables (What's in the Box?)
If you were programming a game, you might need a way to keep track of whether the player is currently falling or safely on her feet. If you were writing software for personal accounting, it would make sense to include a way to keep track of how much money the user has. If you were creating a lending library application, you'd need a way to keep track of the title and author of each book. When it comes to keeping track of information, computers are way ahead of us; and when it comes to computers tracking information, it's all about variables.
Variables are one of the key fundamental elements of programming. You can think of a variable as a box with a name written on the outside. You can put something in the box, look inside to see what's in the box, change what's in the box, and even dump everything out and leave the box empty. But no matter what you do with what's inside the box, the box is still the same box, and it still has the same name written on the outside. That box is your variable, and whatever is in it is the current value of that variable.
Keep an eye on that for me, would you...? Variables are incorporated in pretty much every program, application, or game you've ever used, whether it's your text editor storing a word you copied to the clipboard (above), or World of Warcraft having a detailed list of every piece of armor your dwarf is wearing (below).
You can use variables for all sorts of things: for storing the information a user types into a form, for storing the current day of the week, for storing the current position of the mouse pointer on the screen, and a whole lot more. If you needed a variable to remember a player's score, for example, you would make the following statement to create it:
var playerScore;
The word var is a JavaScript keyword: a word that already means something to JavaScript, so we can use it to tell JavaScript what to do. var tells JavaScript "create a new variable, with the following name"—we call this declaring a variable, and the above example creates a new variable named playerScore. (Note that this is a full statement, so it ends with a semi-colon!).
We chose "playerScore" as the name of that variable—it's the name written on the outside of that metaphorical box. Keep in mind that you can name a variable almost anything. When naming your variables, there are just a few rules to follow:
Variable names must begin with a letter, $ (dollar sign), or _ (underscore). Don't begin a variable with a number or any other symbol like ! or #.
Variable names can only contain letters, numbers, $ (dollar signs), and _ (underscores).
No spaces allowed! And although you can't use a number for the first character of a variable name, you can use a number anywhere after it. For example, 9lives is not a valid variable name, but plan9is.
Variable names are cAsE sEnSiTiVe.
In other words, a variable named PLAYERSCORE is considered different from a variable named playerscore or playerScore. To keep things straight, it's a good idea to name your variables either in all lowercase, or in camelCase. "camelCase" is a common coding practice of pushing all the words in your variable name together (no spaces allowed!), and capitalizing the first letter of each word except the first word. Since the capital letters stand out from the lowercase letters, thatMakesItEasy toReadTheName ofTheVariable. (See?)
Do not use keywords.
Don't use those words that JavaScript already knows, because they're reserved for specific use (which is why they're also known as reserved words). The keyword var, used to create a variable, is one example. You can't use it as a variable name, so var var; would cause an error. For a complete list of JavaScript keywords to avoid as variable names, visit this page at W3Schools.com.
It helps if variable names make sense.
Okay, this one isn't really a rule, but rather a guideline. If you're naming your variables things like value1 or thing, it's easy to lose track of what they are and what they refer to. Imagine rummaging through boxes in the basement, looking for your old gym clothes, and eventually finding them in a box marked "Stuff Box B"—if you'd had them in a box marked "Old Clothes" or "Sports" you'd have found them a lot faster! Giving your variables relevant, understandable names like streetAddress or xCoordinate will help a lot as your programs get more and more complex, so it's a good habit to get into now.
Once you declare a variable, you'll tend to want to store a value in it, which is known as defining the variable. (An undefined variable is no fun for anyone, including the variable.) For example, at the beginning of a game, the player's score starts at zero; so you can start off declaring a variable and giving it a value of 0, like this:
var playerScore;
playerScore = 0;
The = sign is used to assign a value to your variable—to put that stuff in the box! The variable's name is on the left side, the = sign is in the middle, and the value you want to assign to it is on the right. Conveniently, JavaScript lets you declare a variable and assign a value all in one step:
var playerScore = 0;
That single statement creates the playerScore variable and assigns it a value of 0 right away.
You can also declare more than one variable on the same line, like this:
var playerScore, playerLives, healthBars;
That statement creates three variables at the same time, named playerScore, playerLives, and healthBars respectively. Even better, you can combine the technique of declaring multiple variables with the technique of assigning values to them:
var playerScore = 0, playerLives = 3, healthBars = 5;
As you can see, though programming might seem like a challenge, JavaScript is trying to make things as easy as possible for you. With little tricks like this, you can get a lot done with very little code, which is a good goal to strive for. A program that has a lot of functionality without a lot of coding is a program to proud of—it'll be smaller, faster, and more portable. Lots of code put in where simpler code would do is known as bloated code, and it's something we should aim to avoid as a matter of habit.
All this just to wipe soup off your chin? Cartoonist Rube Goldberg could be considered the undisputed master of bloated code. But he didn't have to worry about bandwidth or processor speed—just about making his contraptions funny.
Operators (The Tools of the Trade)
If expressions and values are the "nouns" of JavaScript, and variables are the "proper names" (which we can use to call out the right nouns), then operators are the verbs. With operators, we can actually do stuff to the variables we declare and the values we assign, creating useful expressions and getting some real action going in our programs.
You've already seen one operator in action earlier: the = sign, which is called the assignment operator because it assigns values to variables. You may also have noticed other operators in the examples of expressions that we looked at. Here's a useful list of some of the operators you'll be using as you learn to write scripts:
=Assignment.
As you know, this one assigns a value to a variable: playerScore = 0;
+Addition.
Use the plus sign to add one value to another: playerScore + bonusPoints
-Subtraction.
Use the minus sign (the basic dash/hyphen) to subtract one value from another: playerScore - penaltyPoints
*Multiplication.
Use the asterisk to multiply one value by another: playerScore * 2
/Division.
Use the forward-slash to divide one value by another: playerScore / 2
There are plenty of other operators, some of which we'll explore later in this lecture. The important thing to remember is that operators do the work of putting things in our "boxes" (variables), looking inside them, taking stuff out, or changing what's in there; they affect (and examine) the values of expressions.
Let's go ahead and see how easily operators do their job by putting together a quick script and seeing what results we can get. In your text editor, open a new document and write the following code into it.
<!DOCTYPE html>
<html>
<head>
<title>An HTML Page</title>
<script type="text/javascript">
var playerScore = 50;
var bonusPoints = 100, penaltyPoints = 50;
alert(playerScore);
</script>
</head>
<body>
</body>
</html>
Note that we've declared three variables and assigned values to them (two of them, cleverly, in the same statement!). Save this file as operators.html and load it into your browser. If you've done everything correctly, you should see the player's initial score pop up in the dialog box. (If not, try downloading the example3_operators.html file from the course downloads and compare your code to see what went wrong.)
Now, though, let's make a slight adjustment to our code. This is the code inside our <script> tags, with only the highlighted part changed:
var playerScore = 50;
var bonusPoints = 100, penaltyPoints = 50;
alert(playerScore+bonusPoints);
Save the HTML file and reload your page in the browser. You'll find that the pop-up now adds the value of bonusPoints to the value of playerScore before displaying the results. This is because you've put that expression into your code! Try it again, only this time, revise the same line in a different way:
var playerScore = 50;
var bonusPoints = 100, penaltyPoints = 50;
alert(playerScore-penaltyPoints);
Save the file again, and reload the page in your browser. Now you should see the result of subtracting penaltyPoints from playerScore. And one more time, let's make a change to the same statement:
var playerScore = 50;
var bonusPoints = 100, penaltyPoints = 50;
alert(playerScore*4);
Save your file, reload the page in your browser, and check out the latest result—JavaScript multiplied the playerScore value by 4 before reporting it. This will work with any valid values, variables, and operators you put into that expression inside the parentheses. JavaScript will evaluate the expression, and give you the correct answer when you load the page.
Smooth operators. Operators let you create a literally infinite number of possible expressions for JavaScript to evaluate.
Feel free to experiment with this, changing the expression between the parentheses after the word "alert" and before the semi-colon. See how the order of operations works (remember PEMDAS!). Try two values (numbers) instead of variables. Try several values or variables with different operators. (You might even see what happens if you use the assignment operator in there—though be cautious about where you put it!).
If you run into an error, you can always change the line back to one you know already worked and go from there. With a program this simple, the worst thing that'll happen is it just doesn't work—you can't blow anything up! The more you experiment, the more you'll get the hang of how JavaScript evaluates your expressions, and the more fluent you'll become in communicating with your programs.
Functions (Statements Were Made, Arguments Were Exchanged)
Now that you've got a good grasp of statements, expressions, variables, and operators, you're about to take your first step into the Serious Business of programming.
Using operators and variables, you can put together all sorts of expressions. But what you do with those expressions requires a bit more. And when you have a lot to say—a lot of statements to make—you're going to need something that hits a little harder than line after line of statements. That's where functions come in.
Remember when I said that you might want to put a bunch of related statements together in the JavaScript version of a "paragraph"? That's what a function is...but it's also more than that. You should also remember that mantra I pointed out: only have to write the code once. Because that's one of the huge advantages that functions give us.
When would you need a function? Think of it this way:
If you write the same set of statements more than once in your program, then you probably want to write a function that can perform those statements with whatever values you might need.
If you write the same complicated expression more than once in your program, then you probably want to write a function that can re-create that expression with whatever values you might need.
A function is a set of statements that work together to accomplish a task that's a little too complicated for one statement to do on its own. But the cool part is that, once you write a function, you can use it as many times as you need it! So if you need to do some complex procedure on one value, and then the same complex procedure on another value, you've already got the function written, and you can re-use it. It's like making a special tool for a situation that comes up a lot: once you've made the tool, it's in your toolkit to stay, and you can apply it as needed.
The anatomy of a function is pretty simple, but also specific. Here's an example:
function squareNumber(num) {
return num * num;
}
That's just about as basic as a function can get. We can take it apart piece by piece to see how it works.
functionkeyword
This is just like the var keyword that declares a variable, but here we're declaring (and defining) a function: we're making that function and telling JavaScript how it works.
The function name.
Function names work exactly like variable names; all the same rules and suggestions apply. In the example, I'm defining a function that squares a number (multiplies it by itself), so I went with a simple function name that says exactly what it does: squareNumber.
(argument)
Inside a function, arguments are variables that you can call by name to get their values—they work just like variables we might declare and use outside of the function, but we declare them in the (parentheses) and assign them values when we call the function (ask it to do its job). You can have more than one argument, separated by commas like (name, telephone, street, city), and you can even have no arguments for a function, like ()—but no matter what, you must include the parentheses after the function name (even if you have no arguments!). Above, my example function accepts one argument, which it will call num.
{function definition}
After the parentheses, you have a set of {curly braces}, inside of which you write the statements that make up your function—these {curly braces}define the function, very much like the = assignment operator defines a variable. Whenever you call your function, these are the statements it will execute, using any arguments you send it.
returnkeyword
The JavaScript keyword return is what functions use to "answer" whoever called them. You call a function and send it arguments as needed, and it can return a value determined by the statements and expressions inside it. Not all functions have a return statement in them; sometimes, their job doesn't require them to return a value.
So our squareNumber function asks for a value that it will refer to (while it's on the job) as num; then it multiplies num by itself (squaring it) and returns the result. In a program, we can call our function with a statement like this:
var bigNumber = squareNumber(15);
All we've done here is declare a variable named bigNumber, and used the assignment operator to assign it the value returned when we call our squareNumber() function, sending it a value of 15 as an argument. Since we defined what it does, the function will evaluate 15 * 15 and return the result (225), which will be assigned to our new variable. We can send any valid expression as an argument:
var bigNumber = squareNumber(2+3); // bigNumber is 25
var bigNumber = squareNumber(2*3); // bigNumber is 36
var smallNumber = 3;
var bigNumber = squareNumber(smallNumber); // bigNumber is 9
Our function will always take what it's given and (if told to) return a corresponding result. You should also notice that we can send any variable to our function, no matter what its name is. When its value is used inside the function, it will be known by the name of the argument, but we don't have to give it that same name outside of the function just to send it as an argument. Basically, the function has its own "box" (with its own name marked on it), and the contents of our box are copied into it temporarily so it can do its job properly; nothing that happens to the function's copy will directly affect the original.
Arguments? Agree to disagree! A function takes what you send it and gives it whatever name it likes. That won't affect the original variable you send; whatever happens to the value inside the function stays inside the function.
Here are some important rules to know about functions:
Statements inside functions still end in a semi-colon; but you're not required to put a semi-colon after the closing } curly brace.
Not all functions return a value. Sometimes a function just does stuff, but doesn't offer a value in return.
You must always include the (parentheses) after a function name when you define or call it. When defining it, the parentheses establish what arguments it accepts, even if the answer is none. When calling it, the parentheses let JavaScript know you're calling a function—you want it to actually do some work—instead of just talking about it.
Anything that happens in the function, stays in the function. Just like Las Vegas, a function is sort of a "getaway" from the rest of the program. Sending a variable will not change the value of your original variable; the function will work with its own copy exclusively, leaving the original unaffected. Other than information you specifically send back from a function (like with the return command), once the function finishes its job, your program forgets everything that happened in there. The next time you call the function, it's completely "new"—like three guys with a serious hangover in Vegas, the function has absolutely no memory of the last time you called it.
So to call a function that doesn't accept any arguments, and doesn't return any value, you could write a statement as simple as this:
someFunction();
Assuming the function someFunction was already defined, this is a valid statement—someFunction will be called, do whatever it's supposed to, and then the program will continue right where it left off, just after that call to the function. (Note that this is a complete statement—it tells JavaScript to do something—and therefore ends with a semi-colon.)
As a matter of fact, you've been using a function throughout this lesson already: the alert() function, one of JavaScript's many built-in functions (it's already declared and defined before you write your program, so you can just use it whenever you like!). This function accepts one argument—the message you want to display—and doesn't return anything. Inside the function, all it does is take advantage of the dialog box all browsers provide to give the user your message, like this.
There's no need to be wary of functions—they're one of the most valuable tools in our kit as JavaScript programmers. So let's create a function and call it to demonstrate just how easy it is!
Create a new document in your text editor, and start it off with the basic "skeleton" of an HTML page with JavaScript. You should know how to do this by now—don't forget to put your <script> tags into the head (or body) of your HTML, like this:
<script type="text/javascript">
</script>
Save your file as functions.html, and next add some scripting between your <script> tags.
function playWithNumbers(a, b, c) {
var answer = (a + b) * c;
alert(answer);
}
That's a pretty basic function right there. It accepts three arguments, does some math with them (and assigns the result to a new variable), and then pops up a dialog box with the result. Notice that you do not need to put a semi-colon after the closing } curly brace of the function definition, but you do need to put a semi-colon at the end of each statement inside your function definition.
Save your file, and load the HTML page in your browser...
...hey, nothing happened! Don't worry, though. Remember, we've defined our function, but we haven't actually called it yet. If you never call a function, it'll never actually run. Go ahead and add the following code to your script, after you've defined the function (after the closing } curly brace!) but before your closing </script> tag.
playWithNumbers(2, 3, 4);
All we've done here is call the function that we defined, sending it some values as arguments. Just about any valid expressions work as arguments; I chose those numbers arbitrarily. Remember that typing the name of a function followed by (parentheses) (with any necessary arguments inside those parentheses) is a full statement, which says "Run this function (with these arguments)"—so it needs a semi-colon at the end of the statement.
Save your HTML file again, and reload it in your browser. Now you should see some action!
If that didn't work for you, you can check the example4_functions.html file in the course downloads. But as long as you remember to define your function, and call it with a simple statement, you shouldn't have much trouble getting these to work.
Try experimenting with both the function and the arguments you send. You can send different numbers and see how the math turns out. You can change the expression that's assigned to your answer variable, and see what the result is. The important thing is that it's your function—you decide how it works, and what you want to do with it.
Data Types (A Little from Column A, A Little from Column B)
There's one more basic building block we need to get to, but before we do, it'll help if we look closer at one we've already met: variables.
As you already know, variables store values, composed of data—just a fancy word for information—that we want our programs to remember for later use. But not all kinds of data are the same. If you wanted to keep track of how many times a user clicked a particular button, you'd want to use a number, so you could keep adding to it as you go. If you wanted to keep track of the user's name, you'd need more than a number—you'd need a whole bunch of letters all put together. This is where the type of data you're using comes into play.
Some other programming languages can have a lot of different data types, and many of those languages use strict typing, which means that once you decide what type of data a variable holds, that's it—you can't suddenly decide it's a different type later on. Those programming languages are usually very efficient and powerful, and they use strict typing to make things easier for the computer.
JavaScript, on the other hand, likes to make things easier for us, the programmers. (Good news, huh?) It has a limited number of data types and uses what we like to call duck typing. Basically: if it looks like a duck, and it swims like a duck, and it quacks like a duck, we might as well say "Yeah, it's a duck" without getting a DNA sample. That means that if a JavaScript variable does all the things that a specific type of variable is supposed to do, we can assume it's that data type, and treat it as such with no trouble. Better yet, we can change what data type any variable holds on the fly, and even interpret some data types as others if we don't go too crazy with it.
Duck, duck...goose? Eh, close enough. All three are adorable, delicious, and surprisingly vicious if you approach them in the park.
While there are technically five data types in JavaScript (plus a couple of "subtypes" of one, and two other things that can act like data types), we're just going to focus on three of them for now: number, string, and Boolean. Let's check 'em out!
Numbers (You Can Count on Them)
Values of the number type are exactly what you would expect them to be: numbers! To use them, you simply type out the number as you would normally, made up of any digits from 0 to 9 (along with a . decimal point or a - negative sign—only if you need them!), with nothing extra added. The following are examples of assigning valid numbers to variables:
var year = 1989;
var price = 4.99;
var temperature = -12;
Note that you can type fractions in—after all, a fraction is really just one number divided by another—but by the time JavaScript does anything with them, it'll just convert them to estimated decimals. How accurate the decimals are depends on how many decimal places there might be.
var oneQuarter = 1/4; // JavaScript will make this 0.25
var closeToPi = 22/7; // JavaScript will make this 3.14...
The operators that you've learned so far, like +, -, *, and /, will all work on numbers exactly as you might think (doing addition, subtraction, multiplication, or division respectively). Of course, the = assignment operator can't assign something to a number, or to any plain value; it can only assign values to variables, not the other way around.
// This code will give you an error!
4 = 20 - 16; // Don't do this!
20 - 16 = 4; // Or this!
// But this works just fine!
var num = 20 - 16; // No problem!
There are a few other interesting operators you can use with numbers, which you'll learn about in your first exercise.
Strings (The Thread of Conversation...)
A string is an easy data type to recognize, because it brings us right back home to human languages that we all know—a string is just a set of letters, numbers, punctuation, and other characters that you might expect to read in any book or in the text of any Web site. Because strings have so many more possibilities than numbers—including digits themselves—they can be a little more complex, but no more difficult to use.
When you type out a string value, you must enclose it inside quotation marks, one before and one after, like these:
var firstName = "Alice";
var lastName = 'Dodgson';
var nationality = "British";
var birthday = '4 May, 1865';
var age = "";
(Yes, that last one is a string, not a number—because it's enclosed inside quote marks!).
It doesn't matter if you use "double quote marks" or 'single quote marks', but you must use them consistently when typing a single string value. You can't start with ' and end with " or vice versa.
Also: you can't use fancy quotes to enclose strings, either double or single. Straight quotes only! That's one reason why you shouldn't use a word processor to write code—they'll often turn your straight quotes into fancy ones automatically.
// Correctly typed strings
var color = 'blue';
var animal = "monkey";
// Incorrectly typed strings
var fancyColor = chartreuse;
var fancyAnimal = cockatiel;
var mismatchedColor = 'plaid";
var mismatchedAnimal = "platypus';
In the last two incorrectly typed strings above, the string never closes, which will cause errors in your program. Your closing quote mark has to match your opening one. But why does JavaScript let us use either one? That's simple: it's so that we can include those two characters (" and ') in strings when we want to!
var restaurant = "Mel's Diner";
var mustSeeTv = 'The TV show "Silicon Valley" on HBO.';
As long as you haven't hit a quote mark that matches the first one, you're still inside the string, as noted by the underlines above. And you can use the other quote mark as many times as you like!
Another tip for typing strings: you can put both kinds of quote marks into a string by using a special character. If you enclosed your string with 'single quote marks', you can include one in the string by typing a \backslashimmediately before the single quote you want to have in your string; the same holds true for double quotes.
var restaurant = 'Stop by Mel\'s Diner and say "Hi!"';
var mustSeeTv = "HBO's \"Silicon Valley.\"";
That \backslash tells JavaScript: "Okay, the very next character? I know it's the string closer here, but just put it in the string—I'm not actually closing the string yet." It only works for the quote mark right after the backslash—if you want two in a row, you'll need to backslash both of them individually like \"\". And by the way, don't worry: when JavaScript displays the string to the user, it will not show them the backslash; only we programmers looking at the code itself will see it!
By the way: if you want to put an actual backslash in your string for any reason, you can do so by backslashing the backslash like \\. Every pair of backslashes puts one backslash into the string for you. The backslash is technically known as an escape character: it escapes the "normal" behavior of the character immediately following it in a string, like a closing quote or an escaping backslash.
Like numbers, strings can be "added together" using the + addition operator—technically, this is known as concatenation. What does it look like when two strings are added? Simple—it looks like a new string consisting of the first string followed by the second string.
These guys had the right idea.Sesame Street's two-headed monster was a master of concatenating strings.
Keep in mind that concatenating a string will not add anything—that is, if you want (for example) a space between the first string and the second, you'll need to include it yourself. You can add as many strings—or variables containing strings—together as you like, though, and they'll be arranged in the order you add them.
(Notice that it doesn't matter if you use "double-quoted strings" along with 'single-quoted strings' in the same expression, as long as each individual string is consistent with its own opening and closing quotes.)
As for the other operators we've learned, the -, *, and / operators don't really do anything useful with strings. (Personally, I don't know what "dog" multiplied by "cat" might equal, and I don't want to know. The horror....)
One more bit of info, which will come in handy for your first exercise: strings are cAsE sEnSiTiVe, just like JavaScript code. So the string "Hello world!" is not equal to the string "hello WORLD!". That's something to keep in mind: if you're getting input from your user, but you want to give them some leeway on UPPER- and lowercase typing, you'll need to program that allowance in yourself—JavaScript won't do it automatically. (That's foreshadowing for the exercise, by the way!).
Booleans (Give Me a "Yes or No" Answer)
Finally, let's look at one more data type: the Boolean value. It's without a doubt the single simplest type of data we work with, but for that reason, it can be hard for programming newcomers to wrap their minds around the idea.
Boolean variables are named for George Boole, a nineteenth century English mathematician and logician credited with formalizing the way we think of information. At its most basic, logic is about figuring out if something is true or false; and that is, in fact, the basis of Boolean variables, which can only have one of those two values: true or false.
One or the other. Like a light switch, your Boolean values can only be one way or the other: on or off, true or false. (There are no dimmers in JavaScript!).
That may seem like a simplistic view of the world, with everything in black and white, but for a program it's the thing that makes everything else fall into place. We can know if a user is signed in (true!), or if they still haven't made their latest subscription payment (false!).
What's more, though, is that we can know if the user's age is 18 or over—if one number is greater than another number—or if their last name is the same as yours—if one string is the same as another string. These are still "yes or no" questions, which means they have Boolean answers (true or false). And that amazingly useful fact is what makes all advanced programming possible, because it leads us to one more basic building block of JavaScript...
Comparisons and Conditionals (Not All Variables are Created ==)
If all you could do was store data and regurgitate it so the user could see what it was, that wouldn't be much of a program! In order to create really useful programs, we need to be able to find out what the user wants, analyze data, and make decisions about what to do next depending on that data. Decision-making in JavaScript (and all programming) is known as flow control—you're giving the program a way to control which path it takes and why—and by far the most often-used method of flow control is the conditional statement.
Conditionals—"If" Statements ("Ands" or "Buts" come later...)
In plain English, the structure of a conditional statement goes like this:
If X is true, then do Y.
Which, translated into JavaScript, looks like this (just an example, since it has a rather useless statement in there):
if (x) {
y;
}
So what's going on here? A conditional, also known as an if statement (or if-then statement) is almost like a special kind of function. In our "argument" (in parentheses), we're taking advantage of Boolean values to ask a "yes or no" question. If the answer is yes—the Boolean value is true—then the statements inside the if statement's {curly braces} will run (just like it was a function being called!).
So what can we put in that conditional part—the part in parentheses? A moment earlier, we talked about how any yes or no question is considered a Boolean value. That means we can make comparisons between any two expressions, and get a result of true or false (both of which are reserved JavaScript keywords, by the way!).
To do that, we use another set of operators, much like the ones you already know—but these are the comparison (or logical) operators. Here are some of the most commonly used comparison operators:
==is equal to
This operator gives you a value of true if two expressions have the same value.
!=is not equal to
This operator gives you a value of true if two expressions do not have the same value. The ! translates from JavaScript to English as "not."
<is less than
This operator gives you a value of true if your first expression has a lower value (numerically) than your second expression.
>is greater than
This operator gives you a value of true if your first expression has a higher value (numerically) than your second expression.
<=is less than or equal to
This operator gives you a value of true if your first expression has a lower value than your second expression, or if they have the same value—you can also think of it as "not greater than."
>=is greater than or equal to
This operator gives you a value of true if your first expression has a higher value than your second expression, or if they have the same value—you can also think of it as "not less than."
There's an important distinction to be made here between the = assignment operator and the == comparison operator—don't confuse the two! Remember: it's a single= if you want to tell JavaScript a value, and a double== if you want to ask JavaScript a value.
Similar faces, different jobs. The = assignment operator tells JavaScript what the values are; the == comparison operator asks JavaScript what the values are.
In action, these comparison operators might look like the examples below. Note that these are not complete, valid statements—just examples of conditionals you might use! They are, however, valid expressions, since JavaScript can evaluate them and return a value (of true or false).
// Some conditionals - not full statements!
(num==5) // true if num has a numeric value of 5
(name!="Gina") // true if name is notGina
(luftballons<100) // true if luftballons is less than 100
(bottles>99) // true if bottles is more than 99
(heartRate<=50) // true if heartRate is 50 or less
(age>=18) // true if age is 18 or more
It's important to remember that Booleans can only be true or false—there's no middle ground. So if any of the above expressions don't give you a true value, they'll give you a false value. If you used them as a conditional in an if statement, and got a false value from them, then the statements inside the {curly braces} would not run—JavaScript would simply move along to the next part of the program after the } closing brace.
The best way to understand conditional statements is to try them out and follow the logic. So let's see how an "if" works in practice.
As always, create a new document in your text editor, pop in a basic HTML skeleton, and get your <script> tags set up. We're going to define a function that uses a conditional statement to decide how to respond to the user. To start with, type the following code into your script:
function oldEnough(age) {
if (age<13) {
alert("You aren't old enough to see a PG-13 movie.");
}
}
Can you follow the logic in this conditional statement? Our expression is age<13. If the value that is sent to our function is less than a value of 13, then that whole expression's value will be true...and the alert statement inside the conditional will happen. If the argument's value is not less than 13, that means it is 13 or greater—then the expression's value is false, and any statements inside the if statement's {curly braces} will not happen. This is the very simple but powerful effect of Boolean values and conditional statements—you can tell your program to make decisions based on the information it receives!
Of course, you haven't called your function yet. Let's add another statement to our script to do that:
oldEnough(10);
Save your file as conditional.html and load that HTML file into your browser. (You can compare your code to the course downloads example5_conditional.html file if you have any problems.) Since the value you're sending is 10, and that's less than the 13 which the conditional statement compares it to, you should get an alert box popping up telling you that you can't get into the movie.
You can change the value you send to your function and see what happens. Try changing that last statement to this:
oldEnough(25);
Our new value, 25, isn't less than the 13 it gets compared to in your conditional statement. So in this case, the expression's value will be false (25<13 is not true)...and the alert code won't run!
That's a little bit anti-climactic, though, isn't it? The function we currently have will warn the kids that they can't get in, but it will not let everybody else know that they're free to buy a ticket. That silence, in this case, does not speak volumes—it doesn't speak at all. So let's fix that!
If-Else (The Other Shoe Drops)
To fix our lack of activity when the conditional isn't true, we're going to extend our logic just one more step with an if-else statement. Change your function to look like the following code (the highlighted bits are where I've changed it):
function oldEnough(age) {
if (age<13) {
alert("You aren't old enough to see a PG-13 movie.");
} else {
alert('You can buy a ticket for a PG-13 movie.');
}
}
Save your file and reload it in your browser. If the value you're sending is still 25 (or anything 13 and up), you'll see the new message!
The else, like the if, is a JavaScript keyword that helps guide our program through some logical decision-making. You can think of the else as the "alternative" choice: if the expression evaluates to true, then the first bit of code will run; but if the expression evaluates to false, then the alternative bit of code will run instead.
It's like when you're a little kid, and your mom says: "If you clean your room, I'll give you ice cream. Otherwise, I'll take away your bicycle." (That's one strict but logical mom!). She gives you a condition: "you clean your room." If that condition is true, then one thing happens (ice cream!); if it's not true, then the other thing happens (no bike rides today...). All we're doing is translating that decision-making process from English to JavaScript.
Or else, kiddo. Maybe you should just clean up your room.
Wrapping Up Lecture 1 (Building with Your Blocks)
Okay, take a breather! It feels like you're learning a lot in one lesson, I know. And you are! As you continue through the course, you won't have quite so much thrown at you all at once, but this "crash course" in basic JavaScript is important to get you ready for all the cool stuff you're going to do later.
So what have we learned so far? Well, let's do a quick re-cap.
JavaScript is an object-oriented, client-side programming language.
You can embed JavaScript code in an HTML page, or put it in an external file that more than one HTML page can link to.
Statements are single commands or actions.
Expressions are evaluated by JavaScript and turned into a value based on the values, operators, and other expressions (including variables) that we put together.
Variables are like "boxes" that we can put values inside, to store data and check on it later.
Operators are tools we can use to create expressions, to assign or alter what we put in our variables, and to compare the values of different expressions.
Functions are sets of statements that we can run whenever we need them, and we can send different arguments each time to change the results.
Values (and the variables that hold them) can be of different data types, including number, string, and Boolean.
We can impose flow control on our programs using conditional statements like if or if-else to evaluate the Boolean (true or false) value of expressions and make decisions based on the results.
With such thorough fundamentals, you're going to be able to build on this knowledge to expand your skills far beyond what you've already learned. In fact, we're going to do that straight away, in your first exercise: get ready to put these skills to good use!
Understand the Document Object Model (DOM) of HTML pages. Examine how DOM elements are referenced using CSS selectors to alter the appearance of a document. Learn how to set up a basic jQuery skeleton within an HTML doucment. Assume control over the DOM, using jQuery and CSS selectors to alter the appearance and behavior of your document. Learn how to use jQuery to get information about the current state of DOM elements.