JavaScript Methods
In this reading about JavaScript methods, we will be using methods for several kinds of objects, but not defining or implementing methods. We'll also talk about JS object literals as collections of data, but not yet in the sense of supporting method invocation.
Our first example will be to use the JavaScript Date
object, which is
built into the language.
Displaying the Date Dynamically¶
We can display the current date and time on a web page. For example:
If you reload this page, you'll notice that the date and time change appropriately.
Before we explain the JavaScript code that can do this, we need to
understand how time is represented in JavaScript. We begin by creating a
Date
object:
var dateObj2 = new Date();
As we've seen before, the keyword var
in var dateObj2
creates a new
variable named dateObj2
for storing a value. What we haven't seen
before is the keyword new
, which causes a JavaScript object to
be created. In this case, the object represents the current date and
time. JavaScript comes equipped with lots of pre-defined object types
like Date
.
We can extract information from a Date
object by invoking
methods on it. The table below shows some of the important
methods that Date
objects understand. The elements of the
Value column are dynamically computed by evaluating the JavaScript
expressions in the Expression column, so reloading the page will
update these appropriately.
Expression | Value | Notes |
---|---|---|
dateObj2.getFullYear() | Full year | |
dateObj2.getYear() | Avoid this! Varies from browser to browser | |
dateObj2.getMonth() | 0=Jan, 1=Feb, ..., 11=Dec | |
dateObj2.getDate() | 1 to 31 | |
dateObj2.getDay() | 0=Sun, 1=Mon, ..., 6=Sat | |
dateObj2.getHours() | 0 to 23 | |
dateObj2.getMinutes() | 0 to 59 | |
dateObj2.getSeconds() | 0 to 59 | |
dateObj2.getTime() | Milliseconds since Jan 1, 1970 (the "epoch") |
- state, which is given by what JavaScript calls properties.
- behaviors, which are specified by what JavaScript calls methods.
now
contains a date object. The expression to the left of the dot in
dateObj2.getDate()
is a variable, now
, that
contains a date object. To the right of the dot is the name of the thing
we want to compute based on the object. In this case, we invoke the
getDate()
method, which returns the numerical day of the
month in a date object. (You can tell we're calling a method rather than
selecting a property by the presence of parentheses after the name.)
W3 Schools has a [complete list of Date
methods](http://www.w3schools.com/jsref/jsref_obj_date.asp)
Date Formatting
Now let's return to our date and time display. A date object contains a collection of information about the date and time, but for human-readability, we will need to format that data in some conventional way, using, for example, slashes and commas to separate the various numbers. Here is JavaScript code that creates the correct string. (Next time, we'll look at how to insert it into the document using the DOM). Let's examine the code. The first statement creates aDate
object representing the current date and time, and stores it in a variable
named dateObj
. Subsequent statements extract components of
this Date
object and piece them together.
As shown below, we could get by with only the single variable
dateObj
. Although the other variables are not strictly
necessary, they can help to make the code more readable. Note that
there's nothing special about naming the variable dateObj
.
We could have called it anything else, such as today
or
now
or fred
(but fredwould not be a good name, since it wouldn't suggest the meaning or value of the data).
var dateObj = new Date(); var current_date = ( (dateObj.getMonth() + 1) + "/" + dateObj.getDate() + "/" + dateObj.getFullYear()); var current_time = ( dateObj.getHours() + ":" + dateObj.getMinutes() + ":" + dateObj.getSeconds());## Other Date Methods We've used the example of dates to teach you about: * Objects (encapsulations of data and methods to operate on it) * methods (ways to extract or modify the data in an object) Lots of other objects and methods exist in JavaScript. Here's another method, this time on numbers, the
toFixed()
method. Note that you'll have to open the
JavaScript console to see the output.
The toFixed()
method returns a string representation of the
number, with the number of decimal places given by the argument. It does
not change the value of the variable, as the last step shows.
## Other Date Functions
The earlier date manipulation code was all numerical. That's partly
because JavaScript is global, and they decided not to have a built-in
function to map month zero to Januarywhen it could just as easily have been Janvier (French), Enero (Spanish) or Styczen (Polish). Despite this, we decided to implement a simple function that maps month-numbers (ranging from 0 to 11) to English month-names. Try it out: How would you print the name of the month 10 months from now? ## Array Methods Here are some handy [methods for JavaScript arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) * `push` adds a new element onto the end of an array * `pop` removes and returns the last element of the array * `shift` removes the first element of an array * `unshift` adds an element onto the front * `indexOf` searches for an element and returns its index (-1 if not found) * `splice` optionally removes some elements from the middle and optionally inserts some * `slice` copies an array Try them out. The following uses `JSON.stringify` to convert an array into a string, so that we can print it easily. We'll learn more about that function later. ## the `forEach` method Arrays also have a `forEach` method that takes a *function* as its argument, invoking the function for each element of the array. The function is invoked with 3 arguments: the array item, its index in the array, and the array. (You don't usually need the last argument.) ## JavaScript Object Literals It's now time to return to talking about JavaScript objects in general rather than just date objects. In JavaScript, an object is a collection of data (properties and methods. This collection can be arbitrarily complex, including having other objects inside the containing object (much like a folder can contain other folders), but for now let's keep it simple:
A object is a collection of properties (also called keys) and values. We use the properties (keys) to look up the values. We'll use the termsWe'll ignore methods for now and focus on properties. Let's be concrete. Imagine that we have an object to keep track of a user's info, including their name, year of graduation and whether they're going to the party. So, the three properties will be: 1. `name` 1. `gradYear` 1. `going` We'll begin with a particular person, Alice, who is the class of 2019 and is going to the party. We'll store all that info in a single object and we'll store the object in a variable calledpropertiesandkeysinterchangeably
person1
. We can
make a second object about another person, Betty.
Consider the following JavaScript code:
var person1 = {name: "Alice", gradYear: 2019, going: "yes"}; var person2 = {name: "Betty", gradYear: 2020, going: "no"};
Try copy/pasting that code into a JavaScript console. Look at the resulting objects:
>>> person1 >>> person2JavaScript even has a cool
dir
feature that breaks out all
the properties into separate, clickable things. This is particularly
useful for big, complicated objects, such as windows. Try it:
>>> dir(person1) >>> dir(window)Let's repeat those assignment statements, together with an abstraction:
var person1 = {name: "Alice", gradYear: 2019, going: "yes"}; var person2 = {name: "Betty", gradYear: 2020, going: "no"}; var person2 = {prop1: value1, prop2: value2, prop3: value3};The things on the right hand side are called object literals. The syntax of an object literal is an opening brace, a series of property/value pairs separated by commas, and a closing brace. Each property/value pair consists of a property (which follows the same rules as the names of variables), a colon, and a value. The value can be any JavaScript value, such as a number, string, or another object. Each of these object literals has three property/value pairs, but a JavaScript object can have any number of pairs, including none:
var empty_person = {};## JSON The JavaScript Object Notation is pretty simple and easy to read: * braces around key:value pairs * key:value pairs separated by commas * keys separated from values with a colon * keys are strings * values are either * atomic data like strings, numbers, and booleans, or * compound data like arrays or objects Because of this simplicity and readability, JavaScript Object Notation (JSON) has become very popular for passing data around the web. To turn a data structure into a JSON string, use `JSON.stringify()`. To reverse that operation, use `JSON.parse`: ## Object Operations Given an object, there are a few things you might want to do to it: * Retrieve the value associated with a property * Modify the value associated with a property * Add a new property/value pair * Remove a property/value pair Here are some specific examples of those operations with the `person1` object: You'll notice that the way we add a new property/value pair is identical to the way we modify an existing property/value pair: just an assignment statement. That's because JavaScript creates the property if necessary, and then updates the value. In practice, removing a property/value pair is rarely done, so we really only need to remember two operations: getting and setting. Here are two assignment statements that demonstrate both getting and setting. On the right hand side, we get a value out of one object and on the left hand side we set a value of an object. The syntax for getting and setting look the same: a variable, a dot, and a property. The markers on a Google Map are another example of objects. Those markers are objects with properties like
lat
and lng
(latitude and longitude), along with other info. For example, something
like:
var marker1 = {lng: 42.296612,lat: -71.301956}; // Wellesley** Unknown or Odd Properties The syntax we learned above to get and set a value in an object (
variable.property
) is simple and effective but fails in two
cases: if the property is unknown and if the property contains odd
characters, such as spaces or hyphens.
For example, suppose instead of calling the property gradYear
,
we wanted to call it grad year
(with a space in it). The
following doesn't work at all:
person1.grad year = 2020;Usually, we can get around this very simply by limiting ourselves to property names that don't have spaces, hyphens, semi-colons and other oddities. A slightly more difficult case comes where we don't know the property in advance. For example, we have an object that stores the dimensions of an image, with properties
width
and height
. We
want to retrieve the larger dimension, and we've stored the property in a
variable called larger_dim
. The following fails, because it
tries to look up a property named larger_dim
instead of one
named height
.
There is a solution to both problems: the syntax to get/set a value in an
object can be a string in square brackets. Here's an example that works.
Note that the expression in the square brackets is a literal string.
Here's the same syntax used to solve the second problem of an unknown
property. Note that here, the expression in the square brackets is a
variable (larger_dim
) that contains a string.
In fact, if you want to, you can always use the square bracket notation,
and ignore the dot notation. For example:
However, most programmers appreciate the brevity and reduced punctuation
of the dot notation, so you will see it a lot.
## Looping over an Object's Properties
Sometimes it's useful to be able to loop over all the properties of an
object. JavaScript has a built-in syntax, a special kind of loop, for
doing just that. For example, the following will alert all the properties
in an object:
The following variation alerts all the values in an object. Note that
using the square bracket notation is necessary here, because each time
through the loop the variable prop
has a different value.
The syntax for this loop is
for ( var P in OBJ ) { // loop body here }The
P
is a new variable and we declare it here to
avoid creating a global variable. It is given a value (as if by an
assignment statement) before each time through the body of the loop. Those
values will the properites of the object. The OBJ
is an
existing variable that holds an existing object.
Here's one last example, which counts the number of properties in an
object.