JavaScript

Notes

At its core, JavaScript is another programming language, like C and PHP. Similar to PHP, JavaScript is a dynamically typed, interpreted language. Web browsers, like Internet Explorer, Chrome, and Firefox, support the ability to run JavaScript code associated with a website. These browsers offer an API, or Application Programming Interface, for manipulating a webpage. This means that JavaScript in the browser can be used to manipulate the content, appearance, and behavior of a web page.

Here's a simple example of a "Hello world"-like program, written in JavaScript, coupled with a webpage. Notice the following line in the HTML file:

<script type="text/javascript" src="hello.js"></script>

This HTML tag, the "script tag," allows an HTML document to reference JavaScript code, whether in an external file (as indicated by the src attribute), or inside the tag itself. The code there will start executing immediately [1]. Unlike C, JavaScript has no main method: the code in the file simply starts running.

In hello.js, we've added some JavaScript. Fortunately, the syntax of JavaScript isn't all that different from C and PHP. JavaScript offers a built-in function, called alert, that we are using to display a message to the user. The message we're passing is just the string literal, "Hello, world!"

[1] http://www.w3schools.com/tags/tag_script.asp

When you open the index.html page in your browser, you'll see a dialog box like this.

The syntax for variable declarations in JavaScript is slightly different from that of C and PHP. Variable declarations in JavaScript take the form

var <name> = <value>;

for local variables.

Notice that in these declarations, no type is specified, unlike variable declarations in C.

Also, the type of a JavaScript variable can change throughout the execution of a program. Here, the type of b was originally "boolean," which we can check using the typeof operator [1]. Then, we assigned a string to b, making the new type of b be a "string." If you did something analogous in C, the compiler would complain, but here, it's perfectly valid. [2]

[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

[2] Though, it's a good idea to be careful with changing types too much: strive for good design!

JavaScript loops are similar to loops in C.

Like in C and PHP, you can use functions in JavaScript to make code more reusable, clean, organized, and readable!

Function declarations in JavaScript don't specify the types of the arguments, or the return type. In fact, it's also acceptable for a function to return values of different types. For example:

function giveMeANumber(num)

{

if (num < 0)

{

return "this is a string";

}

else

{

return 3.1

}

}

Also, JavaScript supports anonymous functions: functions without names. Notice that in the second declaration of the sum function in the slides, an anonymous function is seemingly "assigned" to a variable in a variable declaration. This is because functions in JavaScript are treated like values, too: they can be assigned to variables, passed into other functions, etc. We'll see some uses of this later.

JavaScript also offers arrays, which have the same conceptual purpose they have in C and PHP.

arr declaration:

  • One way to declare an empty array.
  • Commonly referred to as "literal array notation."

arr2 declaration:

  • Literal array declaration for an array of size 3.
  • Elements separated by commas.
  • Array access using index notation.
  • Zero-indexed, just like C and PHP.
  • .length property for length of array.

arr3 declaration:

  • Literal array declaration for an array of size 3.
  • The members of an array do not need to have the same type.
  • It is okay for the elements of an array to change types, as we did by assigning a string in the third position.
  • Unlike C, it is acceptable to add an item to an array beyond its initial bounds, as we did by assigning a string in the 101th position of the array. The space between the third element and the 101th element will be filled with undefined values.

[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

JavaScript also offers objects, which are conceptually similar to structs in C, and associative arrays in PHP.

You can use objects to organize related information.

emptyObject:

  • Literal object declaration (JSON: JavaScript Object Notation)
  • Two ways to set properties.
  • Similarly, two ways to access properties.

JavaScript also offers objects, which are conceptually similar to structs in C, and associative arrays in PHP.

You can use objects to organize related information.

Note that an array is one of the properties of this object (the tfs property). Any value can be associated with a property of an object, including objects, functions, booleans, and numbers!

Here, we have an array of objects!

HTML (and more generally, XML) documents are organized into a hierarchical tree structure. Can you see how the tree chart at left corresponds to the HTML document at right? Think about how the title element in the document corresponds to node in the tree, and how it's representable as a child of the head node.

The object structure we've seen in JavaScript gives us a handy way to represent this document as a JavaScript variable, and that's what the concept of DOM (Document-Object Model) is all about. If we have access to an object representation of the document, then we can manipulate the document like we manipulate objects, a way that is convenient and simple. That's really the magic and joy of JavaScript in the browser: the ability to manipulate the document programatically.

  • document.title is a programmatic representation of the HTML document's title. You can use this property of the document object to access and set the title of the webpage. When you receive a new Facebook notification, and the title of the page changes from "Facebook" to "(1) Facebook," this is what's behind-the-scenes!
  • document.body is a programmatic object representation of the HTML document's body. The body, with all of its child elements, is represented in this single structure.
  • One property of the document.body object (and any element object) is innerHTML, which is a string version of the HTML inside this element. Other interesting properties include children, id, and attributes.
  • document.getElementById is a function that allows you to access the object representation of a DOM element with a given id. [1]
  • document.getElementsByClassName is a function that allows you to access a collection of the object representations for all of the elements with a given class. Remember that ids within a document should be unique, while class names can (and likely should) be used multiple times within a document. [2]
  • document.getElementsByTagName is a function that allows you to access a collection of the object representations for all of the elements with a given tag name. For example, to fetch all of the paragraph elements on a page, you could use document.getElementsByTagName("p") [3]

[1] https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById

[2] https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName

[3] https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByTagName

Coding on the client side, in the browser, offers us some exciting opportunities. Within a browser, there are lots of things that, simply put, "happen." For example:

  • The page finishes loading.
  • The user clicks on a button.
  • The user moves the mouse over a paragraph element.

We can use the features of JavaScript to set up code that is event-driven in nature: that is, code that executes in response to an event.

Consider the above code example. Notice that we are assigning an anonymous function to window.onload. onload is a special, global property whose value can be a function. If it is a function, the browser will run this code when the page is completely finished loading. This is useful, because we may only be able to run certain JavaScript code when all of the DOM elements are on the page and ready to work with!

Notice that inside of this function, sometimes referred to as a callback, we access an element of the document (whose id is search_button). Then, we attach a callback function to the search button's onclick property. Can you guess what event this corresponds to?

[1] https://developer.mozilla.org/en-US/docs/Web/API/Event

Slides ( / )

study50 slide
study50 slide
study50 slide
study50 slide
study50 slide
study50 slide
study50 slide
study50 slide
study50 slide
study50 slide
study50 slide
study50 slide
study50 slide

Title Title Title Title Title

Add code in title.js that fetches the title of the document and updates the title so that it is the old title repeated 5 times ("CS50CS50CS50CS50CS50").

Try out some pseudocode here!
Notice (8): Undefined index: default_code [APP/View/Elements/problem.ctp, line 38]
Notice (8): Undefined index: default_code [APP/View/Elements/problem.ctp, line 38]
To complete this problem, please download the distribution code.

Total Price

In index.html, you’ll see markup for a table that specifies a list of fast food items. Next to each item is its price, and whether or not a certain customer ordered the item. Using JavaScript, in food.js, write code that calculates the total price of all of the ordered items. Using the alert function, report the total price that you’ve calculated to the user.

Try out some pseudocode here!
Notice (8): Undefined index: default_code [APP/View/Elements/problem.ctp, line 38]
Notice (8): Undefined index: default_code [APP/View/Elements/problem.ctp, line 38]
To complete this problem, please download the distribution code.

Events and Fast Food

Add JavaScript code in food.js so that when the user moves his or her mouse over one of the food images, the details about the food item are shown in the table above the set of images. Details about each food item can be found in the foodItems array. The id property of each object in the array corresponds to the id of the image element representing each food.

Try out some pseudocode here!
Notice (8): Undefined index: default_code [APP/View/Elements/problem.ctp, line 38]
Notice (8): Undefined index: default_code [APP/View/Elements/problem.ctp, line 38]
To complete this problem, please download the distribution code.

Videos

study50 video thumbnail

Week 9, Monday

study50 video thumbnail

DOM