Learning the Rules of JavaScript
The purpose of JavaScript is to make your app more dynamic by giving it the ability to do things with data and to interact with the user.
JavaScript is a scripting language. That's a type of programming language that controls other applications (such as a Web browser or word processor, for example). Other examples of scripting languages include VBScript, Perl, Python, and PHP. People generally consider scripting languages more "lightweight," meaning easier to learn and use than a traditional full-fledged programming language such as C or Java. Programmers use scripting languages for all sorts of tasks on the Web and on mobile devices.
The Web is an example of client-server computing. This type of computing divides different parts of an application between the user's computer (the client) and a central computer that services many users (the server).
Because JavaScript code runs in your Web browser rather than on a server, we call it a client-side scripting language. Other popular languages that people use on the Web—such as PHP, Java, Perl, Ruby, Python, and C—run their code on the server and then send the results to the browser. When programming code runs on a server, people call it (surprise!) server-side code.
Traditionally, most of the work in client-server computing has taken place on the server side. Today, however, a typical user's computer actually may have more available computing power than a typical Web server. As a result, it's become advantageous for more of the heavy data processing of the Web to happen on the client side—in the user's Web browser, in other words.
On mobile devices, bandwidth is often at a much higher premium than processor power. In other words, it's more important to reduce the number of times that the app needs to talk to the server than it is to reduce the amount of work the mobile device does. For this reason, mobile Web app developers rely heavily on JavaScript to handle many tasks that traditionally were accomplished on the server and then transmitted to the browser.
There's No "I" in Syntax
Every language has rules—whether it's a spoken language such as English or Chinese or a programming language such as JavaScript. Computers are usually not anywhere near as smart or as flexible as people are, so the rules for talking to computers are generally stricter than the rules for talking to people. But the principles are the same.
The rules of a programming language are its syntax.
Rules for JavaScript Syntax
- Capitalization matters. Although it's perfectly okay to spell a tag <DIV> or <div> in HTML5, JavaScript won't recognize "Window" as being the same as "window."
- Use semicolons (;) to separate statements. Either a new line or a semicolon must separate each statement in a JavaScript program. Line breaks are easy to delete, so to be safe, always end a JavaScript statement with a semicolon.
- Put text in quotation marks. Use single or double quotation marks around text that you want JavaScript to treat as text, rather than as numbers or code. Another name for literal text content in programming language is a string.
Here's a very simple JavaScript program. As is the tradition with any sort of introduction to a programming language, this program's only task is to output the words "Hello, World!" Don't worry . . . things will get more interesting, and useful, soon.
To test this program, follow these steps:
- Create a new HTML5 document in Komodo Edit by selecting New > File from Template from the File Menu. Komodo Edit will create a new file with a basic HTML5 template.
- Paste the code shown above (from <script> to </script>) into the document, anywhere between <body> and </body>.
- Save the file, and click the Preview in Browser button.
Here's what you should see:
Hello, World!
If this isn't what you see, check your program carefully. The slightest mistake, such as a missing quotation mark or parenthesis, will cause the program to malfunction.
Once you've made it through testing the Hello, World! program, let's talk about how it works.
The first thing to notice is that the JavaScript code is inside an HTML <script> element. The <script> element tells the Web browser to treat its contents as a script rather than as HTML. If you attempt to put JavaScript into an HTML page without a <script> block, it won't work. The browser will just print out the JavaScript code to the browser window rather than interpreting and running it.
One exception to the rule that JavaScript must be inside a <script> element is the onclick attribute, which lets you run JavaScript when a user clicks on an HTML element such as a button or link. You'll see an example of onclick in the next chapter.
Variables
If you recall your high school algebra, you know that a variable is a symbol that represents a value we don't know. For example, in this algebraic statement, x and y are variables:
x = 2y
In JavaScript (and in most programming languages), the concept of variables is the same . . . except that variables in programming languages can represent more than just numbers.
A variable is a symbol that represents a value. The value may be a number or a string.
To create a variable in JavaScript, you declare it using the "var" keyword, as in the first line of our Hello, World! program.
This statement creates a new variable called "message." As long as you follow certain rules in your naming of variables, they can be as long or as short as you like.
Rules for Naming JavaScript Variables
- Variable names may not start with a number.
- They can't contain spaces.
- They can't contain punctuation.
- You can't use JavaScript keywords (such as "var") as variable names.
- Variable names are case sensitive. To JavaScript "message," "Message," and "MESSAGE" are all different variable names.
Once you've created a variable, you can fill it up (like an envelope) with data, which is precisely what the next line of our program does. Read on to find out how.
Operators and Output
Operators in programming are similar to operators in mathematics, such as plus (+), minus (-), and so on. There are some differences, however. The most important one has to do with the "=" operator. If you said "equals" in your head when you saw that, pay attention. This isn't the equals operator; it's the assignment operator.
Here's the assignment operator in the Hello World program:
It's called the assignment operator because it sets the value of the variable on the left to whatever is on the right. If it were called the equals operator, that would imply that it's comparing the two things, and there's a separate operator called the "is equal to" operator that handles that task. You'll learn about comparison operators later on.
The distinction between "assignment" and "comparison" is important to understand when you're learning programming. Assignment actively puts something into the variable "envelope" (to use my earlier analogy). Comparison checks to see if the thing that's currently in the envelope is the same as something else.
Finally, we're at the point where the program is ready to do something that you can see! Here's the last line of our "Hello, World!" program:
As you may have guessed, this statement takes the value of the variable that we've named message and writes it into the HTML document. When you read it from right to left, it's almost like English. Often, you'll find that this is the best way to read a line of programming code.
Control Structures and Branching
It's time to learn how JavaScript programs do more complex tasks, such as choosing between multiple paths or repeating code multiple times. To have programs that can serve more than one function, you need to be able to define different paths depending on the input data. In the same way that hoses and plumbing control the flow of water, the next few JavaScript commands you'll learn will help you to control the flow of data.
Commands that control the flow of data in an application are control structures. To see a control structure in action, let's make our app do something that wouldn't be easier to do just by using a simple line of HTML markup: We'll ask it to write out "Hello, World!" 5,000 times.
The statement we've added here is a loop. Loops are control structures whose job it is to repeat one or more commands multiple times. This particular type is a for loop. It has three parts:
- Initialization (i=1) is where you create a variable (i) and assign it an initial value (1).
- The condition (i<=5000) tests the variable to find out if it meets specified parameters. If it does, the for loop will continue; if it doesn't, it won't. In this case, we're checking to see if the value of i is less than or equal to 5,000.
- Modification is where the for loop does something to the variable after every time it's run. In this case, the modification (i++) uses the increment operator (++) to add 1 to the value of the variable with every loop.
(Initialization; Condition; Modification)
When you run this code, the output looks like this:
5,000 times
The final fundamental type of command in JavaScript that we'll cover is branching. It's how programmers say things like, "If this is true, do this. If it's not, do that."
One way to do branching in JavaScript is with the If/then/else statement. Here's an example:
You may have noticed the === symbol. This is the identity operator. It means "is exactly equal to." It is slightly different from the "is equal to" operator (==) in that it compares the variable type (number, date, and so on) as well as its value.
I've included a lot of terms and definitions in this chapter. So before we move on to Chapter 3, I'd like you to play this game. Your score won't count as part of your grade, but playing will help you remember what you've learned.
[#TOGGLE#]
[#TOGGLE#]
Read the clue in the first column, and guess the term. Then read the second column for the answer.
Clue |
Answer |
=== (is exactly equal to) |
Identity operator |
Symbol that represents a value |
Variable |
+ or -, among others |
Operator |
What you see when a program runs |
Output |
An if or then statement |
Branching |
[#TOGGLE#]