JavaScript


JavaScript

I would like to point out that JavaScript has nothing to do with the Java programming language itself. Many people unfamiliar with JavaScript have a real problem with this, thinking that the word Java in JavaScript denotes some kind of relationship. Well, the relationship is similar to the relationship between "pine" trees and pineapples, or apples and pineapples. Yes, they are all distantly related, but that is the end of it.
My first encounter with coding JavaScript was in a web development class that was taught at Penn State as part of a web design certificate program. Impatiently I took the precursors, waiting for the class in which my programming skills would help. About 5 minutes into the class, it quickly became apparent that certain experiences would be more useful JavaScript precursors than others. For example, other than providing somewhere for the JavaScript to go, the HTML class wouldn't be of much use. Knowledge of C or any similar language, such as C++, Java, Pascal, or even PL/I, on the other hand, would go a long way toward helping to learn JavaScript.
In this chapter, I cover the following aspects of JavaScript:

Datatypes

Numeric

In JavaScript, all numbers are 64-bit double-precision floating-point numbers, whether they are floating point or integer. This means that 18,437,736,874, 454,810,624 values divided evenly between positive and negative can be represented in JavaScript. In addition, there are three "special" values, increasing the total to 18,437,736,874,454,810,627. 

String


JavaScript strings are UTF-16 strings or 16-bit Unicode Transformation Formats: character encoding. What it comes down to is that each character in a string is represented in 2 bytes, which means that the potential for display of non-English characters exists. This might not seem like a big deal, but it very well could be when the boss walks into your office and asks about internationalization. Ooh, scary.


Boolean

JavaScript Boolean data types are the standard true/false data types that we've all been exposed to umpteen times, end of story.

Arrays

Although it's not an object type, I've chosen to include arrays here because they are a useful mechanism for grouping related information. A relatively simple data structure, arrays permit the access of information based upon an integer index. In JavaScript arrays, this index begins at zero and increases by one for each element of the array.
An item of interest about arrays in JavaScript is that it isn't necessary for the individual elements of an array to all be of the same type, although it might be a good idea to ignore this capability because it presents a world of opportunities to really screw up. However, some really nice goodies built into JavaScript more than make up for the potential issues that might arise from weak typing.
First things first. Let's take a look at the three ways to define a JavaScript array: defining an empty array, defining an array with a set number of elements, and defining an array with a set number of elements with values. Each of these three ways uses the Array() constructor, as shown in the following snippets:
var one = new Array();
var two = new Array(3);
var three = new Array('red', 'green', 'blue');




Variables
In local scope, the variable is defined within a particular function. The simplest way to explain it is by examining the two functions in Listing . The first function, Jeckle, defines a variable named monster. The second function, Frankenstein, also defines a variable named monster. Because both variables are local, Jeckle's monster is a different monster than Frankenstein's.

Two Local Variables
function Jeckle() {
  var monster = 'Mister Hyde';
}

function Frankenstein() {
  var monster = 'Bob';
}

Global scope refers to variables that are defined throughout the entire page. They are defined in one of two ways, either using a var and declaring the variable outside a function, or omitting the var and declaring it within a function. I don't have a problem with the first method of declaring a global variable, but I have some definite issues with the second. All that it takes is one case of "sausage fingers"; a mistyped variable name, and I'm debugging for hours.
Operators
JavaScript Operators
Operator
Type
Description
a + b
Arithmetic
Addition
a - b
Arithmetic
Subtraction
a* b
Arithmetic
Multiplication
a / b
Arithmetic
Division
a % b
Arithmetic
Modulus, the remainder to division
++a
Arithmetic
Increment by one
--a
Arithmetic
Decrement by one
a = b
Assignment
Set equal to
a += b
Assignment
Increment by the value on the right
a -= b
Assignment
Decrement by the value on the right
a *= b
Assignment
Multiply by the value on the right
a /= b
Assignment
Divide by the value on the left
a %= b
Assignment
Modulus by the value on the right
a == b
Comparison
Equal to, value
a === b
Comparison
Equal to, value and type
a != b
Comparison
Not equal to
a > b
Comparison
Greater than
a < b
Comparison
Less than
a >= b
Comparison
Greater than/equal to
a <= b
Comparison
Less than/equal to
a && b
Logical
And
a || b
Logical
Or
!a
Logical
Not
a + b
String
String concatenation
a=(condition)?b:c
Comparison
Comparison operator
typeof(a)
Special
Returns a string consisting of the operand type
void a
Special
Suppresses the return of a variable
I'll bet you didn't know that typeof was an operator.
Flow Control Statements
The Basics of the JavaScript if Statement
if(a == 1)
  alert('a is one');
else {
  alert('a is not one');

  if(b == 1) {
    if(c == 1)
      alert('Both b and c are one');
  } else
    alert('b is not one');
}
Basic Structure of the switch Statement
switch(number) {
  case(0):
    alert('zero');

    break;
  case(1):
  case(3):
    alert('odd < 5');

    break;
  case(2):
  case(4):
    alert('even < 6');

    break;
  default:
    alert('many');

    break;
}

Looping

The purpose of looping in programs is to execute a series of statements repeatedly, thus cutting down on the required lines to code. This reduction in the number of lines has the advantage of improving the overall readability. In addition, loops allow for a variable number of executions. Personally, loops mean that I don't have to type any more than I have to, but, hey, I'm a hunt-and-peck typist.
Examples of for and for/in Loops
var factorial = 1;
var numbers = new Array(1,2,3,4,5);
var index;

for(var i=1;i < 6;i++)
  factorial *= i;

factorial = 1;

for(var i=5;i > 0;i)
  factorial *= i;

factorial = 1;

for(index in numbers)
  factorial *= numbers[index];

alert(factorial);
Functions
Function That Concatenates Two Strings
function concatenate(a,b) {
  return a.toString() + b.toString();
}
There is a perfectly logical reason for this similarity; my mind-reading machine has been perfected. Either that or I'm aware that the majority of developers know only a couple ways to define a JavaScript function. Which is the truth? I'll give you a hint: It is currently the fall of 2005, and I'm writing this on the SEPTA R5 line on my way to Doylestown, Pennsylvania. If I actually could read minds across space and time, I would have won Powerball last week and I'd be writing this on the beach in Tahiti.
This means that, as web developers, we're all in a rut, doing the same thing the same way day after day and year after year. Yeah, I know the drill: "It works, so why change it?" and "I always do it that way" are usually the statements used. To these statements, I have one response, "You learn more from your mistakes than you do from your successes!"
When you actually get down to it, there are several separate and distinct ways to define a function in JavaScript. Why so many ways to define a function? I can't rightfully say, but I can take a guess. It has always seemed to me that the more ways there are to perform a single task, the more flexible the language is and the more problems can be solved.
Getting back to our function that concatenates two strings, we've already seen one possible method of implementing the solution, so let's take a look at another way. JavaScript has the Function() constructor for, interestingly enough, constructing functions. The Function constructor, an example of which is shown here, is used to create a function and assign it to a variable or an event handler.
var concatenate = new Function('a','b','return a.toString()
+ b.toString()');
In addition to the Function constructor, the function operator can be used to assign a function to a variable. One of the more interesting "features" of the Function constructor is that it shows that JavaScript is really an interpreted language because the function is stored as a string. This is an example of our string concatenation example defined using the function operator:
var concatenate = function(a,b) {return a.toString() + b.toString


Recursion

recursion occurs when a function calls itself repeatedly to achieve some kind of 
result. Some examples of functions that readily lend themselves to recursion are 
mathematical, such as the Euclidean algorithm, the Ackerman Function and the 
functions to compute factorials, Fibonacci numbers, and Catalan numbers.


Event Handling

Event Handlers Common to Most Browsers

Operator

Syntax

Description

blur

object.onblur = function

Fires when an object loses focus, such as when Tab is pressed or another object is clicked.

focus

object.onfocus = function

Fires when the object gets focus, either programmatically or through user interaction.

load

window.onload = function

Fires when the page is loaded. This event can be simulated by periodically checking the document's readystate property.

resize

window.onresize = function

Fires when the window is resized.

scroll

window.onscroll = function

Fires when the page's scroll bars are used.

unload

window.onunload = function

Fires just before the page is onloaded. Although it is commonly used by pop-ups to spawn more pop-ups, it does have some legitimate uses.

onclick

object.onclick = function

Fires when an object is clicked.

dblclick

object.ondblclick = function

Fires when an object is double-clicked.

mousedown

object.onmousedown = function

Fires when the mouse button is pressed.

mouseup

object.onmouseup = function

Fires when the mouse button is released.

mousemove

object.onmousemove = function

Fires when the mouse is moved.

mouseover

object.onmouseover = function

Fires when the mouse pointer moves over the specified object.

mouseout

object.onmouseout = function

Fires when the mouse pointer moves off the specified object.

change

object.onchange = function

Fires when the object's value changes.

reset

object.onreset = function

Fires when the object (form) is reset.

select

object.onselect = function

Fires when a different option is selected on the object (select).

submit

object.onsubmit = function

Fires when the object (form) is submitted.

keydown

object.onkeydown = function

Fires when a keyboard key is pressed when the specified object has focus.

keyup

object.onkeyup = function

Fires when a keyboard key is released when the specified object has focus.

keypress

object.onkeypress = function

A combination of both the keydown and keyup events.




Next Chapter






No comments:

Post a Comment