HTML and CSS Reference
In-Depth Information
var arr = [1, 2, 3];
for (var i = 0, len = arr.length; i < len; i++) {
console.log(arr[i]);
}
You can also express iteration functionally. Every JavaScript array object has a method named forEach,
which takes a function as an argument. forEach iterates over all the array elements, passing each one as
the first argument to the user-defined function, and the second, optional, argument is the element's index
position. Here's how the previous example looks using this method:
var arr = [1, 2, 3];
arr.forEach(function (element, i) {
console.log(element);
});
This code snippet does the same thing as the previous one—printing out each array element value to the
console—but it is structurally different. There are a couple of benefits to this approach. For one, we didn't
declare any temporary variables used only for iteration that linger around after this code has executed. But
perhaps more important, this style allows you to reason about the code at a functional level. This means
you can understand how the code works by examining the function that is passed as an argument and the
parameters it accepts. You do not have to worry about the state of the loop or if any dependent variables
are setup correctly. This can have advantages when debugging, because when something goes wrong,
you can dig down through the function calls in the stack trace to determine where exactly the error
occurred.
The drawback to functional iteration is that it's typically slower than a for-loop, due to the increased
computation needed to execute the function. As is often the case when writing programs, the developer
needs to consider both readability of the code and the speed of its execution, and that can be determined
only by testing. Generally, you should write programs that are clear and easy to understand, and let the
browser makers worry about getting the code to run fast.
We use both kinds of iteration throughout this topic, depending on speed requirements and the need for
clarity. More often, and central to working with JavaScript and the DOM, is the need to pass function
arguments as event handlers. We look at how these work in the next section on user interaction.
User interaction
User interaction is probably one of the main reasons you're reading this topic. After all, if it weren't for
interaction or some sort of dynamic input going into the animation, you might as well watch a movie. User
interaction is based on user events, and these are generally mouse events, touch events, and keyboard
events. Let's quickly go through the various user event types and how to handle them.
Events and event handlers
To understand events, you must understand a couple of additional concepts: listeners and handlers. A
listener determines whether an element should act on a particular event, and a handler is a function that is
called when the event occurs.
 
Search WWH ::




Custom Search