62
BIT116: Scripting Lecture 03 Starting Out With JavaScript

Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

Embed Size (px)

Citation preview

Page 1: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

BIT116: ScriptingLecture 03

Starting Out With JavaScript

Page 2: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

2

Document Structure

Document Appearance

Interactivity

Page 3: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

3

Syllabus Adjusted I updated the ‘Assessment’ section so that it includes the 2 point quiz + 8 points of in-

class work.

Let me know ASAP if you have any further questions

Page 4: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

4

BIT 116: The Big Idea 116 is extra programming review after 115

You’ve seen all these ideas, and most of the syntax is the same You will need to look stuff up here & there to help remind yourself how stuff works

Page 5: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

5

JavaScript Background / Overview

Page 6: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

6

What JavaScript IsJavaScript is a popular general-purpose scripting language used to put energy and pizzaz into otherwise static web pages by allowing a page to interact with users and respond to events that occur on the page.

JavaScript allows for dynamic interaction between the web page and the end-user.

It would be a hard task to find a commercial web page, or almost any web page, that does not contain some JavaScript code.

Page 7: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

7

What JavaScript IsJavaScript is a client-side language designed to work in the browser on your computer, not the server.

It is built directly into the browser (although not restricted to browsers), Mozilla Firefox, Google Chrome, and Microsoft Internet Explorer being the most common browsers.

In syntax, JavaScript is similar to C, Perl, and Java; for example, if statements and while and for loops are almost identical.

JavaScript is an interpreted language, not a compiled language.

Page 8: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

8

What JavaScript Is NotJavaScript is not Java!

A newsgroup wit once quipped that “Java is to JavaScript what Car is to Carpet.” Java is a strongly typed language with strict guidelines, whereas JavaScript is loosely typed and flexible.

Java data types must be declared. In JavaScript variables, parameters, and function return types do not have to be declared.

Java programs are compiled. JavaScript programs are interpreted by a JavaScript engine that lives in the browser.

JavaScript is not HTML, but JavaScript code can be embedded in an HTML document and is contained within HTML tags.

Page 9: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

9

What JavaScript Is NotJavaScript has its own syntax rules and expects statements to be written in a certain way.

JavaScript doesn’t understand HTML, but it can contain HTML content within its statements.

All of this will become clear as we proceed.

Page 10: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

10

Locating JavaScript in a Web Page

Page 11: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

11

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.

Page 12: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

12

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)

The first three are somewhat similar to CSS

Also: right now we’re going to focus on identifying which parts of an HTML page are HTML vs. CSS vs. JavaScript. Don’t worry about the JavaScript code itself!

It’s interesting to look at, you might pick some JS up, but don’t worry about it yet

Page 13: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

13

Inline JavaScript

Page 14: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

14

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 41)

<!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>

FILE: helloworld1.html

Page 15: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

15

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

FILE: helloworld2.html

Page 16: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

16

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.

FILE: helloworld3.html

Page 17: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

17

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.

Page 18: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

18

Internal JavaScript

Page 19: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

19

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>

FILE: helloworld4.html

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

Page 20: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

20

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>

FILE: helloworld5.html

Page 21: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

21

Internal JavaScript

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

function popUp() {alert("Hello Yourself!") // note missing ; - this is

ok}

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

FILE: helloworld6.html

Page 22: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

22

External JavaScript File

Page 23: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

23

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. • Specifically, you do NOT need the <script> tag at the start – the file is already in “JavaScript mode”

• 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. FILES: helloworld9.htmlhelloworld.js

Page 24: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

24

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.

Page 25: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

25

Exercise: Identify CSS, HTML and JavaScript in a fileThis is an important skill

It’s also fairly ‘rote’ – once you understand the rules you can always do this

This can be confusing when you first startLet’s practice this now!

When you get done, move on to the next exercise

Page 26: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

26

Variables

Page 27: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

27

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

Page 28: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

28

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

Page 29: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

29

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.

Page 30: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

30

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.

Page 31: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

31

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.

Page 32: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

32

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 =“doc”, variableName3 = 3.14159;

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

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

alert(variableName1);

Page 33: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

33

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• 1numberOfOranges• number of Oranges• numberOfOranges 2

Page 34: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

34

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.

Page 35: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

35

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.

Page 36: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

36

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;

Page 37: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

37

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).

Page 38: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

38

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).

Page 39: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

39

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.

Page 40: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

40

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.

Page 41: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

41

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.

Page 42: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

42

Variable Data Types: UNDEFINED

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

var myVar;alert(myVar);

myVar = 200;alert(myVar);

Page 43: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

43

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.

Page 44: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

44

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.

Page 45: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

45

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.

Page 46: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

46

Exercise: Adding A Variable

Page 47: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

47

Quick Overview Of JavaScript

• Since you’ve seen much of this in 115• We’ll do a quick overview now• And then cover topics in more detail as we

go

Page 48: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

48

Operators

Operators 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.

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

Page 49: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

49

Comparisons

You’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

Page 50: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

50

Assignments

When 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.

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

Page 51: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

51

A Brief Word About Functions

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

Page 52: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

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

A Brief Word About Functions

For 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 (you'll hear me call 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.

Page 53: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

53

Conditional Code

A 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

Page 54: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

54

The <noscript> Tag

If 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.

Page 55: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

55

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).

Page 56: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

56

Comments

As 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 */

Page 57: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

57

Semicolons

As 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.

Page 58: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

58

White Space and Newlines

Most 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.

Page 59: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

59

Scope

In 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.

Page 60: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

60

Balanced Brackets and Quotes

It 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.

Page 61: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

61

Exercises:

Page 62: Starting Out With JavaScript. 2 Document Structure Document Appearance Interactivity

62

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.

Lecture 3