Home > Sample chapters > Programming > HTML, JavaScript and web development

JavaScript Programming Basics

Basic JavaScript Syntax

In much the same way that learning a foreign language requires studying the grammar and sentence structure of the language, programming in JavaScript (or any other computer language) requires learning the grammar and structure of a program. In this section, you’ll learn some of the syntax of JavaScript.

JavaScript Statements and Expressions

JavaScript is built around statements and expressions, where statements are simple lines of code and expressions produce or return values. Consider these two examples:

  • Statement:

    if (true) { }
  • Expression:

    var myVariable = 4;

In these examples, myVariable is the result, thus making it an expression, whereas nothing is returned from the if (true) conditional. While this admittedly is somewhat nuanced, what you need to know is that JavaScript has a certain structure that’s made up of statements and expressions.

Lines of code are typically terminated with a semi-colon. The exceptions to this rule include conditionals, looping, and function definitions, all of which will be explained later.

One or more JavaScript statements and expressions make up a JavaScript program or script. (These two terms, program and script, are used interchangeably.) You saw examples of JavaScript programs in the previous chapter.

Names and Reserved Words

JavaScript statements and expressions are made up of valid names (known as identifiers in the ECMA-262 specification) and words reserved for JavaScript itself. You saw several reserved words used already in the book. In JavaScript, the following are reserved words and therefore should be used only for their intended purpose; you can’t use these as a variable or function name, for example.

break

delete

if

this

while

case

do

in

throw

with

catch

else

instanceof

try

continue

finally

new

typeof

debugger

for

return

var

default

function

switch

void

Several other words are reserved for future use; therefore, you shouldn’t use these in your programs for your own purposes either.

class

extends

let

public

const

implements

package

static

enum

import

private

super

export

interface

protected

yield

When using JavaScript, you must use certain naming conventions. Valid names begin with a letter, a dollar sign ($), or an underscore (_) and cannot be a reserved word.

The following are valid names:

  • myVariable

  • EMAILADDR

  • SongName

  • data49

The following are invalid names:

  • var

  • 3address

  • deci#

The first example, var, is a reserved word and therefore cannot be used to name your own variables or functions. The second, 3address, begins with a number, and the final example, deci#, contains a special character.

Spacing and Line Breaks

JavaScript largely ignores white space, or the space between elements and statements. Obviously, you need to separate words within a line by at least one space, but if you use two or more spaces, JavaScript typically won’t care. That said, you’ll spend less time chasing down difficult bugs if you just stick to standard single spacing. For example, this is valid:

var myVariable = 1209;

In this example, there’s a single space between the keyword var and the name of the variable, myVariable. That space is required for the JavaScript interpreter to run the code.

Closely related to white space are line breaks or carriage returns, officially known in the JavaScript specification as line terminators. In general, line breaks are not required. In fact, you’ll sometimes see JavaScript programs with no line breaks whatsoever. This is called minification; it reduces the size of the JavaScript downloaded by the visitor. However, I recommend that when you develop your programs, you use standard line breaks after each JavaScript statement and expression.

Comments

Comments are lines within programs that aren’t executed. Comments are frequently used to document code behavior within the code itself. Consider this code:

// myVariable is used to count characters
// Generate an alert when myVariable has more than 10 characters
// because this indicates we've exceeded some business rule.
if (myVariable > 10) {

In this example, there are three lines of comments prior to the if statement.

JavaScript comments come in two forms: single-line comments with a double slash (//), as you’ve seen, and the C-style multiline comment syntax (/* */), so named because of the C programming language. The double slash you saw in the first example is a single-line comment that indicates to the JavaScript interpreter that everything following the two slashes up to the next line break should be ignored.

The multiline comment structure indicates that everything beginning with the opening /* up to the closing */ should be ignored, as in this example:

/* myVariable is used to count characters
 Generate an alert when myVariable has more than 10 characters
 because this indicates we've exceeded some business rule.*/
if (myVariable > 10) {

One important point with multiline comment syntax is that multiline comments can’t be nested. For example, this is invalid:

/* A comment begins here


  /*
   myVariable is used to count characters
   Generate an alert when myVariable has more than 10 characters
   because this indicates we've exceeded some business rule.
  */
  if (myVariable > 10) {

*/

In this example, the interpreter will happily begin the comment where you want it to, but once it encounters the first closing */ sequence it will just as happily close the comment. Things will go haywire when the interpreter encounters the final closing */ sequence, and an error will be the result.

Case Sensitivity

JavaScript is case sensitive. This fact alone trips up many programmers, experienced and new alike. When working with the language, the variable name MYVARIABLE is completely different than myVariable. The same goes for reserved words, and really everything else in the language. If you receive errors about variables not being defined, check the case.

Additionally, case sensitivity is essential for accessing elements from HTML pages with JavaScript. You’ll frequently use the HTML id attribute to access the element with that id through JavaScript. The case of the id in your code needs to match the case of the id as written in HTML. Consider this HTML, which creates a link to an example website:

<a href="http://www.example.com" id="myExample">Example Site</a>

The HTML itself could be written in any case you want—all uppercase, all lowercase, or any combination you’d like. The web browser will show the page the same. However, you’re now a JavaScript programmer, and one thing you’ll do frequently is access HTML from JavaScript. You might do this to change the HTML, create new parts of pages, change colors, change text, and so on. When you access HTML from within JavaScript, the case you use in the HTML suddenly becomes important. For example, you get access to that element in JavaScript with a special JavaScript function called getElementById, which, as the name suggests, retrieves an element using its id attribute, like so:

document.getElementById("myExample");

In this example code, the case of the id attribute’s value (myExample) is essential. Trying to access the element using MYEXAMPLE or myexample or MyExample will not work. Just as important, the JavaScript function getElementById is itself case sensitive. Using GETELEMENTBYID or the more subtle getElementByID won’t work. If you didn’t care about case before, now’s the time to start!

While we’re on the subject of case, it’s good practice to keep case sensitivity going throughout your code, whether it’s JavaScript or something else. This is true both within code and for URLs and file names.

Operators

JavaScript has operators to perform addition, subtraction, and other math operations, as well as operators to test for equality. The math-related operators are the same as those you learned in elementary school math class. You use the plus sign (+) for addition, a minus sign (–) for subtraction, an asterisk (*) for multiplication, and a forward slash (/) for division. Here are some examples:

// Addition
var x = 5 + 3.29;
// Subtraction
var number = 4901 - 943;
// Multiplication
var multiplied = 3.14 * 3;
//Division
var divide = 20 / 4;

Some important operators for programming are equality operators. These are used within conditionals to test for equality. Table 2-1 shows these equality operators.

Table 2-1 Equality operators in JavaScript

Operator

Meaning

==

Equal

!=

Not equal

===

Equal, using a more strict version of equality

!==

Not equal, using a more strict version of inequality

The difference between the normal equality operator (==) and the strict equality operator (===) is important. The strict equality test requires not only that the values match, but also that the types match. Consider this example:

var x= 42;
var y = "42";


x == y  // True
x === y // False

Later in the chapter, you’ll create a sample program that tests these operators.

Relational operators test how a given expression relates to another. This can include simple things such as greater than (>) or less than (<), as well as the in operator and instanceof operator. You’ll see examples and explanations of the in and instanceof operators as they’re used.

There are also operators known as unary operators. These include the increment operator (++), the decrement operator (––), the delete operator, and the typeof operator. As with other operators used in this book, when it’s not obvious, their use will be explained as you encounter them.