77
BIT116: Scripting Lecture 03 Tuesday, July 14 th , 2015 Instructor: Craig Duckett [email protected] JavaScript Buzzwords, JavaScript Variable

Tuesday, July 14 th, 2015 Instructor: Craig Duckett [email protected] JavaScript Buzzwords, JavaScript Variables

Embed Size (px)

Citation preview

BIT116: ScriptingLecture 03

Tuesday, July 14th, 2015

Instructor: Craig Duckett

[email protected]

JavaScript Buzzwords, JavaScript Variables

2

JavaScript Tutorial Cheat Sheet (RECOMMENDED)

http://www.tutorialspoint.com/javascript/javascript_tutorial.pdf

Over the course of the BIT116 class, we will be covering most of the topics and features represented by this tutorial “cheat sheet” from the folks at TutorialsPoint. This is a handy PDF that gathers these topics and features in one brief and well-organized document. It’s use is highly recommended

3

A Note About the Folder Names in the Paths in Browser

Because this is Summer Quarter, we are taking what is typically an 11-week course and compressing it into 8-Weeks. While I have gone through this website and changed the file names and labels on the various web pages to coincide with this 8-week schedule, I have not changed the original names of the folders in which they are contained. As such, going forward, the folder names that display in the path in the browser will not necessarily coincide with the given Lecture name, but this is nothing you need to worry about.

For example, we are now in Lecture 3, but the folder that contains the Lecture 3 files will display Lecture 4 in the browser path. In reality, it doesn’t really matter what the name of the folder is, provided you can successfully access the given files and web pages through the provided links.

As you can see below, the Lecture_03.pptx PowerPoint pack is housed in the Lecture_04 folder in the folder tree:

http://faculty.cascadia.edu/cduckett/bit116/Lecture_04/Lecture_03.pptx

As I stated early, this is nothing for you to worry about going forward. I only wanted to explain what some of you might have seen as a naming discrepancy.

A Quick

Note!

4

Let's Begin With Some JavaScript Buzzwords…

5

ObjectsJavaScript is an Object-Oriented Language

An object is a kind of thing. A dog, a computer, and a bicycle are all objects in the physical world.

To JavaScript, there are objects it deals with in web browsers, such as windows and forms, and the elements of the form, such as buttons, text boxes, check boxes, and so on.

Because you can have more than one dog, or more than one window, it makes sense to give them names. While you could refer to your different pets as Dog1 and Dog2 and Dog3, it’s a bad idea because its easier to tell the dogs apart if they have unique names.

In the same way, all the examples in this BIT116 class will give JavaScript objects their own unique names.

6

Properties

Objects have properties. A dog has fur, the computer has a keyboard, and the bicycle has wheels. In the JavaScript world, a document has a title, and a form can have a check box.

Changing a property of an object modifies that object, and the same property name can be a part of completely different objects. Let’s say that you have a property called empty. It’s okay to use empty wherever it applies, so you could say both that the dog's belly is empty and that the dog's bowl is empty.

Note that the computer’s keyboard and the bicycle’s wheels aren’t only properties; they are also objects in their own right, which can have their own properties. So objects can have sub-objects.

7

Methods

The things that objects can do are called methods. Dogs bark, computers crash, and bicycles roll.

JavaScript objects also have methods: buttons click(), windows open(), and text can be selected(). The parentheses "( )" signal that we’re referring to a method, rather than a property.

One way to wrap your head around this is to think of objects as nouns and methods as verbs.

8

Dot Notation ( or Dot Syntax)You can put together objects, properties, and methods to get a better description of an object, or to describe a process. In JavaScript, these pieces are separated by periods (also known as dots, as in Internet addresses). This is called dot notation or dot syntax. Here are some examples of objects and their properties written in this way:

bicycle.wheelsdog.paws.front.leftcomputer.drive.dvddocument.images.namewindow.status

And here are some examples of objects and methods written in dot syntax:

dog.bark()document.write()forms.elements.radio.click()

9

The Document Object Model (DOM)

On a web page, the objects that make up the page (or document) are represented in a tree structure. You’ve seen this sort of thing before when building HTML pages; the top level of the page is contained in the <html> tag, and inside that you’ll find the <head> and <body> tags, with other tags within each of those, and so on.

JavaScript considers each of the items in the document tree to be objects, and you can use JavaScript to manipulate those objects. The representation of the objects within the document is called the Document Object Model (DOM).

NOT TO WORRY! WE WILL GO INTO DEEPER DETAIL ABOUT the DOM IN OTHER LECTURES

10

The Document Object Model (DOM)

Each of the objects on the tree is also called a node of the tree. We can use JavaScript to modify any aspect of the tree, including adding, accessing, changing, and deleting nodes on the tree.

Each object on the tree is a node. If the node contains an

HTML tag, it’s referred to as an element node.

Otherwise, it’s referred to as a text node.

That’s all you need to know about the DOM and nodes for now; you’ll learn more about them later as the course progresses.

NOT TO WORRY! WE WILL GO INTO DEEPER DETAIL ABOUT the DOM IN OTHER LECTURES

11

EventsEvents are actions that the user performs while visiting your page. Submitting a form and moving a mouse over an image are two examples of events.

JavaScript deals with events using

commands called event handlers. An action by the user on the page triggers an event handler in your script.

The 12 most common JavaScript event

handlers are listed on the right

Event Handlers

NOT TO WORRY! WE WILL GO INTO DEEPER DETAIL ABOUT EVENTS IN OTHER LECTURES

12

EventsIn JavaScript, if the user clicks a button, the onclick event handler takes note of the action and performs whatever duties it was assigned.

When you write a script, you don’t have to anticipate every possible action that the user might take, just the ones where you want something special to occur.

For instance, your page will load just fine without an onload event handler. But you need to use the onload command if you want to trigger a script as soon as the page loads.

NOTE: While JavaScript is CASE SENSITIVE the names of events can oddly be written in lower-case (e.g., onclick), camel-case (e.g., onClick), or upper-case (e.g., ONCLICK) depending on the convention used by the developer. Most developer’s choose all lower-case or camel-case conventions.

13

ValuesIn JavaScript, a piece of information is a value.

There are different kinds of values; the kind you’re most familiar with are numbers.

A string value is characters—such as a word or words—enclosed in quotes.

A boolean tests whether a statement is true or false

Null is used to indicate an empty object

Value Types

NOT TO WORRY! WE WILL GO INTO DEEPER DETAIL ABOUT VALUES TYPES IN OTHER LECTURES

14

Variables

Variables contain values. For example, the variable name is assigned the string “Rex Winkus”. Another way to write this is name = "Rex Winkus". The equals sign is the assignment operator and can be read as “is set to.” In other words, the variable name now contains the value “Rex Winkus”.

JavaScript is case sensitive. This means that name is not the same as Name, and neither is the same as NAME.

NOTE: Variable names cannot contain spaces or other punctuation, or start with a number. They also can’t be one of the JavaScript reserved words.

Reserved Words

WE WILL GO INTO MORE DETAIL ABOUT VARIABLES A BIT LATER IN THIS LECTURE

15

OperatorsOperators are the symbols used to work with variables. You’re already familiar with operators from simple arithmetic; plus and minus are operators.

While both x++ and ++x add one to x, they are not identical; the former increments x after the assignment is complete, and the latter before.

For example, if x is 5, y = x++ results in y set to 5 and x set to 6, while y = ++x results in both x and y set to 6. The operator -- (minus sign) works similarly.

NOTE: If you mix numeric and string values when adding two values together, the result is a string. For example, "catch" + 22 results in "catch22".

Operator Types

NOT TO WORRY! WE WILL GO INTO DEEPER DETAIL ABOUT OPERATOR TYPES IN ANOTHER LECTURE

16

ComparisonsYou’ll often want to compare the value of one variable with another, or the value of a variable against a literal value (i.e., a value typed into the expression).

For example, you might want to compare the value of the day of the week to “Monday”, and you can do this by checking if todaysDate == "Monday" (note the two equals signs).

Comparisons

NOT TO WORRY! WE WILL GO INTO DEEPER DETAIL ABOUT COMPARISON TYPES IN ANOTHER LECTURE

17

AssignmentsWhen you put a value into a variable, you are assigning that value to the variable, and you use the '=' assignment operator to do the job (single equals sign).

For example, you use the equals sign to make an assignment, such as name = "Rex Winkus".

There are a whole set of assignment operators. Other than the equals sign, the other assignment operators serve as shortcuts for modifying the value of variables.

For example, a shorter way to say x = x + 5 is to say x+ = 5.

Assignments

NOT TO WORRY! WE WILL GO INTO DEEPER DETAIL ABOUT ASSIGNMENT TYPES IN ANOTHER LECTURE

EXAMPLE:

X = X + 5X += 5

THESE AREEQUIVALENT

18

A Brief Word About FunctionsBefore we get into the “Accessing JavaScript in a Web Page” examples coming up next, you need to learn a bit about functions, which you’ll use often when writing JavaScript.

SIMPLY PUT: A function is a set of JavaScript statements that perform a task.

Every function must be given a name (with the rare exception of using an anonymous function which we’ll discuss later on in this course) and can be invoked—or “called”—by other parts of the script.

Functions can be called as many times as needed during the running of the script.

NOT TO WORRY! WE WILL GO INTO DEEPER DETAIL ABOUT FUNCTIONS IN ANOTHER LECTURE

19NOT TO WORRY! WE WILL GO INTO DEEPER DETAIL ABOUT FUNCTIONS IN ANOTHER LECTURE

A Brief Word About FunctionsFor example, let’s say that you’ve gotten some information that a user typed into a form, and you’ve saved it using JavaScript. If you need to use that information again and again, you could repeat the same code over and over in your script. But it’s better to write that code once as a function and then call the function whenever you need it. Easy-peasy!

A function consists of the word function followed by the function name. There are always parentheses after the function name, followed by an opening curly brace (if you’ve had me for BIT115, you’ll be familiar with me calling this an "opening squiggle"). The statements that make up the function go on the following lines, and then the function is closed by a closing curly brace (you'll hear me call this a "closing squiggle"). Here’s what an example of what a function looks like:

function sayWhat() { Notice the camelCase

alert("JavaScript is Groovy, Man!");}

Notice that the line with alert is indented. That makes it easier to read your code. All of the statements between the first brace and the last one (and you probably noticed that those two lines are not indented) are part of the function. That’s all you need to know for now about functions.

20

<!DOCTYPE html><html><head><title>Function Example</title></head><body>

<p onclick="sayWhat()">Click me!</p>

<script> function sayWhat() { alert("JavaScript is Groovy, Man!"); }</script>

</body></html>

<!DOCTYPE html><html><head><title>Function Example</title><script> function sayWhat() { alert("JavaScript is Groovy, Man!"); }</script></head><body>

<p onclick="sayWhat()">Click me!</p>

</body></html>

Function Example

Script in <head> Script in <body>

http://faculty.cascadia.edu/cduckett/bit116/Lecture_04/function_example.html

21

Conditional CodeA conditional tells code to run if something is true and possibly if something is not true

if (conditional) {/* then this part */

}else {

/* else this part */}

Another way to say the same thing:

(conditional) ? { /* then this part */} : {/* else this part */ }

Neither way is more “right” than the other.

NOT TO WORRY! WE WILL GO INTO DEEPER DETAIL ABOUT CONDITIONALS IN ANOTHER LECTURE

22

The <noscript> TagIf the user is using an older browser that doesn't support JavaScript or has his-or-her JavaScript functionality disabled, including the <noscript> tag in your HTML code can alert the user that JavaScript is required for proper page functionality.

It is not required to include the <noscript> tag in the exercises and Assignments for this class, but I wanted to reference it in case you see it while you research JavaScript in other web sites or by Goggling it.

23

Case Sensitivity

BE AWARE: JavaScript is case sensitive!When you name a variable or function, pay attention to your uppercase and lowercase letters. myFunction is not that same thing as MyFunction or myFUNCTION or myfunction.

Also, you must refer to built-in objects with the proper casing. Math and Date start with uppercase letters, but not window and document.

Most built-in methods are combined words by capitalizing all but the first, such as getElementById (often referred to as camelCase).

24

CommentsAs with all programming languages—and as we've seen with Java—comments are an important part of the coding process even though they don’t actually do anything in the code itself.

They are helpful hints for other people who might read your code. More often, they can remind you of why you wrote that weird piece of code a month ago.

Single-line comments look like this:

// This is a single-line commentreturn true; // Comment after code

Multiline comments look like this:

/* This comment can wrapinto the next line and eventhe next line and the next */

25

SemicolonsAs with Java, JavaScript statements should end with semicolon like sentences end with a period. Technically they are optional, but that’s only because JavaScript interpreters add them automatically at the end of most lines.

It’s best to get into the habit of adding the semicolons yourself because there can be strange side effects when you let the interpreter do it for you.

All of the demo examples used throughout this class will hopefully demonstrate proper semicolon usage.

26

White Space and NewlinesMost whitespace such as spaces, tabs, and empty lines is ignored in JavaScript and usually just aids readability.

In fact, on large-scale production code, all nonessential whitespace is usually stripped out so that script files download quicker.

In the class examples and demo pages, I’ll try to demonstrate how best to use whitespace for readability.

27

ScopeIn most of the United States, if you claimed "I'm going to Broadway!" people will assume that you're referring to a street in New York City. While the street is in New York, people globally understand your reference. You can think of Broadway as a global.

However, if you're in Seattle and you say you're going to Broadway, people might assume that you're referring to the street on Capitol Hill. This is a local value. In Seattle, not being clear whether you're referring to the local "Broadway" or the globally known "Broadway" can lead to confusion. In Seattle, the default is the locally known version and you have to explicitly state "Broadway in New York City" in order to refer to the other. Outside of Seattle, people will think of New York City's "Broadway" first, unless they too have some other local version of "Broadway."

The scope of each of these streets is where each is the default, i.e., the one that will be automatically thought of if no other identifying information is given.

With JavaScript code, the easiest way to avoid questions about a variable's scope is to avoid using two variables with the same name in two different places doing two different things.

28

Balanced Brackets and QuotesIt is easy to make mistakes when it comes to punctuation.

Remember that every time you open a bracket, such as [ , ( , or { , or a quote mark, such as ' or ", you must close it in the correct order.

It can be trickier than you think.

29

Window Object and Document Object

30

The Window Object and the Document Object

As you learn JavaScript you will be using some code that works with the Windows object and other code that works with the Document object, however the Window object and the Document object are not the same. So, what is the difference between the two? Good question!

The "window" is the first thing that gets loaded into the browser. This window object has the majority of the properties like length, innerWidth, innerHeight, name, if it has been closed, its parents, and more.

What about the document object then?

The document object is your html, asp, php, or other document that will be loaded into the browser.

The document actually gets loaded inside the window object and has properties available to it like title, URL, cookie, etc.

What does this really mean? That means if you want to access a property for the window it is window.property, if it is document it is window.document.property which is more commonly used in short as document.property.

31

32

The Window Object and the Document Object

Windows Object (Properties and Methods)The Windows Object (W3Schools)

Document Object (Properties and Methods)The Document Object (W3Schools)

Examples:

Return URL of Current Page: document.write(window.location.href);

Return Path Name of Current URL: document.write(window.location.pathname);

Load a New Document:

function newDoc(){   window.location.assign("http://www.programajama.com")}

<input type="button" value="Load New Document" onclick="newDoc()">

33

Accessing JavaScript in a Web Page

34

Accessing JavaScript in a Web Page

Web browsers are built to understand HTML and CSS and convert those languages into a visual display on the screen. The part of the web browser that understands HTML and CSS is called the layout or rendering engine. But most browsers also have something called a JavaScript interpreter. That’s the part of the browser that understands JavaScript and can execute the steps of a JavaScript program. Since the web browser is usually expecting HTML, you must specifically tell the browser when JavaScript is coming by using the <script> tag.

The <script> tag is regular HTML. It acts like a switch that in effect says “Hey, web browser, here comes some JavaScript code; you don’t know what to do with it, so hand it off to the JavaScript interpreter.” When the web browser encounters the closing </script> tag, it knows it’s reached the end of the JavaScript program and can getback to its normal duties.

35

Accessing JavaScript in a Web Page

JavaScript can appear in several places:

• Inline (JavaScript inside a tag)• Internal (JavaScript in a <script> tag)• External (JavaScript in a separate file with a .js extension)• Dynamic (In an external file loaded by JavaScript)

36

Inline JavaScript

37

Inline JavaScript

Inline JavaScript appears inside an individual tag. The JavaScript commonly appears inside a event attribute, such as onClick (see below and next slide), or document.write (see Slide 40)

<!DOCTYPE html><html><head><title>Hello World 1</title></head><body><form><input type="button" value="Hello World" onClick="alert('Hello Yourself!')"></form></body></html>

http://faculty.cascadia.edu/cduckett/bit116/Lecture_04/helloworld1.html

38

Inline JavaScript

<!DOCTYPE html><html><head><title>Hello World 2</title></head><body><p><a href="#" onClick="alert('Hello Yourself!')">Hello World</a></p></body></html>

Notice how the a tag has two attributes (properties) with special values:• href attribute is "#" although it might also be empty " ", or contain "javascript:; "

- this disables normal link behavior• onclick attribute is alert('Some Message');

- onclick is an event — the JavaScript runs when the event happens, in this case when the link receives a click

http://faculty.cascadia.edu/cduckett/bit116/Lecture_04/helloworld2.html

39

Inline JavaScript

<!DOCTYPE html><html><head><title>Hello World 3</title></head><body><p><a href="javascript:alert('Hello Yourself!')">Hello World</a></p></body></html>

In this variation, the JavaScript is actually inside the href attribute. This is equivalent to the onClick example—we don’t need to explicitly specify the "click" event, because the href takes care of that for us.

http://faculty.cascadia.edu/cduckett/bit116/Lecture_04/helloworld3.html

40

Inline JavaScript

The above inline examples demonstrate a single line of JavaScript code—the alert() function—which displays a message in a modal dialog box.

Inline JavaScript can be useful for certain specific tasks, but inline should be your third choice.

External JavaScript files should be your first choice, internal JavaScript your second.

41

Internal JavaScript

42

Internal JavaScript

<!DOCTYPE html><html><head><title>Hello World 4</title></head><body><h2>Hello World</h2><script>

// JavaScript goes here, between the opening and closing <script> tags.

// Notice use of "//" comment style while in between the <script> tags.

alert('Hello Yourself!');</script></body></html>

http://faculty.cascadia.edu/cduckett/bit116/Lecture_04/helloworld4.html

Internal JavaScript appears inside a <script> tag, like this:

43

Internal JavaScript

<!DOCTYPE html><html><head><title>Hello World 5</title></head><body><h2>Hello World</h2><h2><script>

document.write("Hello Yourself!");</script></h2></body></html>

http://faculty.cascadia.edu/cduckett/bit116/Lecture_04/helloworld5.html

44

Internal JavaScript

<!DOCTYPE html><html><head><script>

function popUp() {alert("Hello Yourself!")

}</script></head><body><input type="button" onClick="popUp()" value="Hello World"></body></html>

http://faculty.cascadia.edu/cduckett/bit116/Lecture_04/helloworld6.html

45

External JavaScript File

46

External JavaScript File

To use an external JavaScript file in a web page, use the <script> tag with the src attribute pointing to the JavaScript file.

Example:

<script src="somejavascript.js"></script>

When using the <script> tag to load an external JavaScript file, do not also use the tag as a container for internal JavaScript — that is, do not put JavaScript (or anything thing else) between the opening tag and the closing tag.

• External JavaScript files are text files containing JavaScript, and nothing else. • Edit using any text editor. Serious JavaScript developers typically edit files using an Integrated

Development Environment (IDE) such as Dreamweaver or Komodo Edit.• Do not use the <script> tag in an external JavaScript file itself — the <script> tag goes in the web page.• When using two or more script tags on a page, the order of the tags can be significant, in terms of

JavaScript processing.

http://faculty.cascadia.edu/cduckett/bit116/Lecture_04/helloworld9.html

http://faculty.cascadia.edu/cduckett/bit116/Lecture_04/helloworld.js

47

Dynamic JavaScript

“Dynamic” JavaScript Versus JavaScript

Fundamentally, all JavaScript can be considered dynamic. All dynamic means in this context is that the script is performed on the client’s computer rather than on the server. However, “dynamic” most commonly refers to scripts that control, access, or manipulate HTML elements on the page. Dynamic JavaScript used to be called DHTML – Dynamic HTML – however, this term is rather misrepresentative of what’s really going on.

DHTML is differentiated from Ajax by the fact that a DHTML page is still request/reload-based. With DHTML, there may not be any interaction between the client and server after the page is loaded; all processing happens in JavaScript on the client side. By contrast, an Ajax page uses features of DHTML to initiate a request (or 'subrequest') to the server to perform actions such as loading more content.

48

Variables

49

Variables

When programming, you will often want to change the value of a number, text, or other data.

For example, if you are keeping a count of how many oranges you have in a bowl, the number won’t always be the same, since oranges can be added or removed from the bowl at any time.

Suppose you want to store the number of oranges in the bowl someplace – and you want that value to change when the number of oranges changes. To do this in a script, you will need to use a variable.

A variable holds a value in memory which can then be used or changed. For example, if you decided to write down the number of oranges in a bowl, you might write something like this:

Number of Oranges in Bowl: 18

If the number of oranges changed then you would rewrite that number:

Number of Oranges in Bowl: 17

50

Variables

So, as you may recall from the Java class, a variable stores a value that can change as the program executes. When you code a JavaScript application, you frequently declare variables and assign values to them.

Variables are useful because:

• They can be used in places where the value they represent is unknown when the code is written• They can be updated or changed programmatically ( as the program is running)• They can save time in writing and updating scripts• They can make the purpose of the code easier to understand

Pseudocode Example:

totalPrice = 2.50 + 2.25 + 1.99 + 44.50

or

totalPrice = candy + chips + beverage + gas

51

Defining Variables

Now that you understand what variables are and why you want to use them, you need to learn how to make them work in your scripts. You create variables by declaring them. Then you assign values to them using the JavaScript assignment operator, the single '=' symbol. When you name your variables, you need to follow the rules for naming variables in JavaScript, as well as consider the meaningfulness of the name.

Declaring Variables

To declare text as a variable, you use the var keyword (var is short for variable), which tells the browser that the text to follow will be the name of a new variable:

var variableName;

For example, to name your variable numberOfOranges, the declaration looks like this:

var numberOfOranges;

In this example, you have a new variable with the name numberOfOranges. The semicolon ends the statement. The variable numberOfOranges does not have a value assigned to it yet.

52

Assigning Values to a Variable

You can give your variables a value at the same time that you declare them or you can assign them a value later in your script.

To assign a value to a variable, you use the JavaScript assignment operator, which is the equal to (=) symbol. If you want to declare a variable and assign a value to it on the same line, use this format:

var variableName = variableValue;

For example, to name your variable numberOfOranges and give it the numeric value 18, use this statement:

var numberOfOranges = 18;

Here is what each piece of the code above does:

var This is a special keyword in JavaScript that is used to define a variable. numberOfOranges This names the variable numberOfOranges . = This is the assignment operator, which assigns the value on its right side to the variable name on its left side. 18 This is the value that will be assigned to the variable, which in this case will be 18. ; The semicolon ends the statement, and the browser will move on to any additional statements in the code.

53

Assigning Values to a Variable CONTINUED

BE AWARE: As we learned in Java, be careful not to think of the assignment operator (=) as having the meaning “is equal to.” This operator only assigns a value from right to left (left right). The operator for “is equal to” is two (2) equal signs together (==), as we’ll cover again in a later class.

Naming Variables

Before you start naming your own variables, you need to be aware of JavaScript’s naming rules. The factors you need to consider when choosing names are case sensitivity, invalid characters, and the names that are reserved by JavaScript. Additionally, you should try to give your variables names that are both easy to remember and meaningful.

Using Case in Variables

JavaScript variables are case sensitive—numberOfOranges, numberoforanges, NUMBERoFoRANGES and NumberOfOranges are four different variables. When you create a variable, you need to be sure to use the same case when you write that variable’s name later in the script. If you change the capitalization at all, JavaScript sees it as a new variable or returns an error. Either way, it can cause problems with your script. It is for this reason that I like to use camel case when naming my variables (and functions too) and stick with it through all my scripting.

54

Declaring or Declaring/Assigning Multiple Variables

You can declare multiple variables or declare/assign multiple variables at the same time using only one var.

To assign a value to a variable, you use the JavaScript assignment operator, which is the equal to (=) symbol. If you

Without assigned values:

var variableName1, variableName2, variableName3;

With assigned values:

var variableName1 = 10, variableName2 = 20, variableName3 = 30;

You might even do this, but show them on their own lines:

var variableName1 = 10, variableName2 = 20, variableName3 = 30;

55

Naming Variables

Using Allowed Characters

An important rule to remember is that a variable name must begin with a letter or an underscore character ( _ ) or a dollar character ($). The variable name cannot begin with a number or any other character that is not a letter (other than the underscore). The other characters in the variable name can be letters, numbers, underscores, or dollar characters. Blank spaces are not allowed in variable names. So, the following variable names would be valid:

• numberOfOranges• $numberOfOranges• _numberOfOranges • number_of_Oranges• numberOfOranges2

The following variable names are not valid:

• #numberOfOranges starting with a pound sign is a no-no• 1numberOfOranges starting with a number is a no-no• number of Oranges spaces are a no-no• numberOfOranges 2 spaces are a no-no

56

Avoid Using JavaScript Keywords when Naming Variables

Another rule to keep in mind when naming your variables is to avoid the use of JavaScript reserved words. These are special words that are used for a specific purpose in JavaScript. For instance, you’ve learned that the reserved word var is used to declare a JavaScript variable. Using it as a variable name can cause numerous problems in your script, since this word is meant to be used in a different way.

Note that all of these words are in all lowercase letters. Throughout this course, we'll learn how these reserved words are used, so they will become more familiar over time.

57

Variable Data Types

So far, you’ve seen examples of variable values that are numbers.

In JavaScript, the variable values, or types, can include number, string, Boolean, and null.

Unlike stricter programming languages, JavaScript does not force you to declare the type of variable when you define it.

Instead, JavaScript allows virtually any value to be assigned to any variable.

Although this gives you flexibility in coding, you need to be careful because you can end up with some unexpected results—especially when adding numbers.

58

Variable Data Types: Numbers

JavaScript does not require numbers to be declared as integers, floating-point (decimal) numbers, or any other number type.

Instead, any number is seen as just another number, whether it is 7, –2, 3.453, or anything else. The number will remain the same type unless you perform a calculation to change the type.

For instance, if you use an integer in a variable, it won’t suddenly have decimal places unless you perform a calculation of some sort to change it (dividing unevenly, for instance). As you’ve seen, you define a number variable by using the keyword var:

var variableName = number;

Here are some examples:

var payCheck = 1800; var phoneBill = 35.50; var savings = 1.50; var spareTime = -24.5;

59

Variable Data Types: Numbers CONTINUED

If you need to use a particularly long number, JavaScript supports exponential notation.

To denote the exponent, use a letter e right after the base number and before the exponent.

For example, to create a variable named bigNumber and assign it a value of 4.52 × 105 (452,000), put the letter e in place of everything between the number and the exponent (to represent the phrase “times 10 to the power of”):

var bigNumber = 4.52e5; // this means move the decimal point 5 to the right

NOTE: JavaScript may return an answer to a calculation using exponential notation (like many calculators).

60

Variable Data Types: String

String variables are variables that represent a string of text. The string may contain letters, words, spaces, numbers, symbols, or most anything you like. Strings are defined in a slightly different way than numbers, using this format:

var variableName = "stringText";

Here are some examples of string variables:

var myRide = "2011 Nissan Rogue";var myOldRide = "2001 Nissan Frontier (currently in Arizona)";var myPC = "Dell Core i7 Processor, 16GB RAM, 500GB SSD & 2TB SATA HD";var myOldPC = "Dell Pentium 4, 6MB RAM, 500GB SATA HD";var gobbledyGoop = "Wuzzup, dude? Groovy! I am @ home 4 now just chillin...";

As you can see, strings can be short, long, or anything in between. You can place all sorts of text and other characters inside of string variables. However, the quotation marks, some special characters, and the case sensitivity of strings need to be considered (which I'll discuss momentarily).

61

Variable Data Types: String CONTINUED

Matching the Quotation Marks

In JavaScript, you define strings by placing them inside quotation marks (quotes, for short), as you saw in the examples.

JavaScript allows you to use either double quotes (" ") or single quotes (' ') to define a string value. The catch is that if the string is opened with double quotes, it must be closed with double quotes.

var myRide="2011 Nissan Rogue";

The same goes for single quotes:

var myHomeTown='Mountlake Terrace, Washington';

BE AWARE: Trying to close the string with the wrong type of quotation mark, or leaving out an opening or closing quotation mark, will cause problems.

62

Variable Data Types: String CONTINUED

Using Special Characters

Special characters enable you to add things to your strings that could not be added otherwise.

For example, suppose that you need a tab character between each word in a string. If you press the TAB key on the keyboard, JavaScript will probably see it as a bunch of spaces. Instead, use the special character \t, which places a tab in the string, as in this example:

var myPets="Schatzie\tOlive\tKC";

In each spot where the special character \t appears, JavaScript interprets a tab character.

63

Variable Data Types: String CONTINUED

Using Special Characters CONTINUED

If you want a single backslash character in your string, you need to use the special code for a backslash: \\. For instance, suppose you wish to write the following sentence on a Web page: “Go to the directory c:\javascript on your computer.” If you use the string as it is written, your code would look like this:

document.write("Go to the directory c:\javascript on your computer.");

The problem is that the single backslash would not be printed on the Web page. It would appear as

Go to the directory c:javascript on your computer

To fix this, use the \\ special code to print a single backslash on the page:

document.write("Go to the directory c:\\javascript on your computer.");

Now you get the sentence you want printed to the browser, like this:

Go to the directory c\:javascript on your computer.

NOTE: We will learn more about the document.write() method in the next few classes

64

Variable Data Types: String CONTINUED

Using Special Characters CONTINUED

Suppose that you want to print a sentence on a Web page with strong emphasis. JavaScript allows you to print HTML code to the page as part of a string in the document.write( ) method (which we will learn more about in the next few classes).

To print in bold type, you could just add in the <strong> and </strong> tags from HTML, as in this sample code:

document.write("<strong>JavaScript Rules!</strong> This is fun.");

Which would print this on the web page:

JavaScript Rules! This is fun.

NOTE: We will learn more about the document.write() method in the next few classes

65

Variable Data Types: String CONTINUED

Using Special Characters CONTINUED

66

Variable Data Types: String CONTINUED

Using Special Characters CONTINUED

Now suppose that you want the code itself to appear on two lines when it is viewed, like this:

JavaScript Rules! This is fun.

You might try this by adding the newline special character \n to the code:

document.write("<strong>JavaScript Rules!</strong>\nThis is fun.");

The \n special code is only a newline in JavaScript (as when you're working with a string variable); it will not result in an HTML line break. The JavaScript newline code does not add a new line to the result of the code shown in the browser display. If you want to add a line break in the browser display, you need to use the HTML <br> tag to produce it. Keep in mind that the JavaScript newline affects only the appearance of the source code; it does not play a factor in the end result. However, it does help later when you want to format the output of JavaScript alert boxes and various other JavaScript constructions.

NOTE: We will learn more about the document.write() method in the next few classes

67

Variable Data Types: String CONTINUED

Escape Characters

JavaScript allows you to escape certain characters, so that they will show up correctly and avoid causing errors. Like special characters, escape sequences use the backslash character (\), which precedes the character that needs to be escaped. As noted earlier, JavaScript checks each string for the presence of special characters before rendering it. This is useful if you want to have a quote within a string.

For example, suppose that you want to print the following sentence on a Web page:

John said, "JavaScript is easy."

What would happen if you just threw it all into a document.write() command?

document.write("Rex said, "JavaScript is easy."");

If you look near the end of the document.write() line, you will see when the double quote is used before the word JavaScript, the browser thinks you have closed the string used in the document.write() command and expects the ending parenthesis and semicolon. Instead, there is more text, and the browser gets confused.

68

Variable Data Types: String CONTINUED

Escape Characters CONTINUED

To avoid problems with quotes, use the backslash character to escape the quotation marks inside the string. By placing a backslash in front of each of the interior double quote marks, you force them to be seen as part of the text string, rather than as part of the JavaScript statement:

document.write("Rex said, \"JavaScript is easy.\"");

This fixes the problem with the string, and the sentence will print with the quotation marks.

69

Variable Data Types: String CONTINUED

Escape Characters CONTINUED

The escape technique also works for HTML code in which you need quotation marks. For instance, if you want to put a link on a page, you use the anchor tag and place the URL in quotes. If you escape the quotes in the anchor tag, JavaScript allows you to write the HTML code to the page within the document.write() method, as in this example:

document.write("<a href=\"http://someplace.com\">Text</a>");

This does the job, but there is also an easier way to make this work if you do not want to escape quotation marks all of the time.

To avoid escaping the quotes in the preceding code, you could use single quotes around the URL address instead, as in this code:

document.write("<a href='http://someplace.com'>Text</a>");

You can also do this the other way around if you prefer to use single quotes on the outside, as in this example:

document.write('<a href="http://someplace.com">Text</a>');

70

Variable Data Types: String CONTINUED

Escape Characters CONTINUED

The important point to remember here is to be sure that you do not use the same type of quotation marks inside the string as you use to enclose the string. If you need to go more than one level deep with the quotes, you need to start escaping the quotes; this is because if you switch again, it will terminate the string. For example, look at this code:

document.write("Rex said, 'Mulligan says \"Hi!\" to someone.'");document.write("Rex said, 'Mulligan says "Hi!" to someone.'");

The first one would work, since the quotes are escaped to keep the string going. However, the second line only switches back to double quotes when inside the single quotes within the string. Placing the double quotes there without escaping them causes the string to terminate and gives an error.

As you can see, quotation marks can be a real pain when you need to use a large number of them within a string. However, remembering to use the backslash to escape the quotes when necessary will save you quite a few headaches when you are looking for a missing quote. I’ve had to look for missing quotes in my code a number of times, and my head was spinning after a few of those encounters! Later on in this course, you will see that you can add strings together, which can simplify the use of quotes for you.

71

Variable Data Types: Boolean

A Boolean variable is one with a value of true or false. Here are examples:

var RexCodes = true; var RexIsNotCool = false;

Notice that the words true and false do not need to be enclosed in quotes. This is because they are reserved words, which JavaScript recognizes as Boolean values.

Instead of using the words true and false, JavaScript also allows you to use the number 1 for true and the number 0 for false, as shown here:

var RexCodes = 1; // 1 means "true" var RexIsNotCool = 0; // 0 means "false"

Boolean variables are useful when you need variables that can only have values of true and false, such as in event handlers (these will be covered in a later class).

NOTE: When we talk about the concept of a Boolean variable, the first letter of the word Boolean is capitalized (because it is derived from the name George Boole). However, the JavaScript reserved word boolean is written in all lowercase letters when you use the keyword in a script.

72

Variable Data Types: NULL

Null means that the variable has no value. It is not a space, nor is it a zero; it is simply nothing.

If you need to define a variable with a value of null, use a declaration like this:

var variableName = null;

As with the Boolean variables, you do not need to enclose this value in quotation marks as you do with string values, because JavaScript recognizes null as a keyword with a predefined value (nothing).

Null variables are useful when you test for input in scripts, as you’ll learn later on in this course.

73

Variable Data Types: UNDEFINED

An undefined value is given to a variable that has not been assigned a value yet.

74

Using Variables

Now that you know how to assign values to variables, you will want to know how to use them later in your script. To use a variable, you simply type the variable name where you need to use its value. For example, you can pop up an alert message in the browser using window.alert():

window.alert("Hello World");

This could be altered to use a variable instead, like this:

var message = "Hello World"; window.alert(message);

The result will be the same: an alert with the text Hello World in it.

Notice that you do not need quotes around the variable name since it was already defined as a string.

75

Using Variables CONTINUED

When a value is used multiple times within a script and you need to change that value, it can be a pain to keep up with changing that value in every spot it was used in the code. This is where variables provide a great advantage: you can simply update the value of the variable once, and the variable will use that new value in each place it is called.

For example, if you wanted to alert Hello World several times, you could simply use the message variable each time:

var message = "Hello World";window.alert(message);var numberOfOranges = 18;var numberOfApples = 9;var numberOfBananas = 6;window.alert(message);

The above code would send the Hello World alert twice. The other code between the alerts does not change the value of the message variable, so it will use the same value for the second alert.

76

Using Variables CONTINUED

When you are coding, there will be times when you will need to change the value of a variable and make use of the new value. The example we have been using provides a good case for a change – visitors could become quite irritated by getting not only another popup alert, but one with the exact same message as the first!

To make this a little less annoying, let’s try changing the message before the second alert is sent to the viewer.To change the value of a variable, you can simply assign it a new value. Given our example, you could do this:

var message = "Hello World";window.alert(message);message = "How are you?";window.alert(message);

Notice that the var keyword is not used again. This is because the variable has already been defined, and we are simply giving it a new value. Now, when the code is run, the second message will be How are you? rather than a duplicate of the Hello World message.

You can change the value of a variable as many times as needed, which gives you plenty of flexibility once you have defined a variable. You can alter string values, perform calculations on numbers, or do other things.

77

Please begin working on the LECTURE 3 In-Class Exercises.

When you have completed your ICE, call the Instructor over to verify your work. If you have questions about your work, please call over the Instructor to clarify.

Once you have completed your ICEs, you are free to go for the day.

If you don't finish your ICEs by the end of class, you will still get full credit for actively doing the work, but it is greatly recommended you finish any outstanding ICEs outside of class.

ICE 03