Book Image

Object-Oriented JavaScript - Second Edition

Book Image

Object-Oriented JavaScript - Second Edition

Overview of this book

JavaScript is the behavior, the third pillar in today's paradigm that looks at web pages as something that consists of clearly distinguishable parts: content (HTML), presentation (CSS) and behavior (JavaScript). Using JavaScript, you can create not only web pages but also desktop widgets, browser and application extensions, and other pieces of software. It's a pretty good deal: you learn one language and then code all kinds of different applications. While there's one chapter specifically dedicated to the web browser environment including DOM, Events and AJAX tutorials, the rest is applicable to the other environments Many web developers have tried coding or adopting some bits of JavaScript, but it is time to "man up" and learn the language properly because it is the language of the browser and is, virtually, everywhere. This book starts from zero, not assuming any prior JavaScript programming knowledge and takes you through all the in-depth and exciting futures hidden behind the facade. Once listed in the "nice to have" sections of job postings, these days the knowledge of JavaScript is a deciding factor when it comes to hiring web developers. After reading this book you'll be prepared to ace your JavaScript job interview and even impress with some bits that the interviewer maybe didn't know. You should read this book if you want to be able to take your JavaScript skills to a new level of sophistication.
Table of Contents (19 chapters)
Object-Oriented JavaScript Second Edition
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Preface
Built-in Functions
Regular Expressions
Index

Array


The Array constructor creates array objects:

> var a = new Array(1, 2, 3);

This is the same as the array literal:

> var a = [1, 2, 3]; //recommended

When you pass only one numeric value to the Array constructor, it's assumed to be the array length.

> var un = new Array(3);
> un.length;
3

You get an array with the desired length and if you ask for the value of each of the array elements, you get undefined.

> un;
[undefined, undefined, undefined]

There is a subtle difference between an array full of elements and an array with no elements, but just length:

> '0' in a;
true
> '0' in un;
false

This difference in the Array() constructor's behavior when you specify one versus more parameters can lead to unexpected behavior. For example, the following use of the array literal is valid:

> var a = [3.14];
> a;
[3.14]

However, passing the floating-point number to the Array constructor is an error:

> var a = new Array(3.14);
Range Error: invalid array length

The Array.prototype members

Property/method

Description

length

The number of elements in the array.

> [1, 2, 3, 4].length;
4

concat(i1, i2, i3,...)

Merges arrays together.

> [1, 2].concat([3, 5], [7, 11]);
[1, 2, 3, 5, 7, 11]

join(separator)

Turns an array into a string. The separator parameter is a string with comma as the default value.

> [1, 2, 3].join();
"1,2,3"
> [1, 2, 3].join('|');
"1|2|3"
> [1, 2, 3].join(' is less than ');
"1 is less than 2 is less than 3"

pop()

Removes the last element of the array and returns it.

> var a = ['une', 'deux', 'trois'];
> a.pop();
"trois"
> a;
["une", "deux"]

push(i1, i2, i3,...)

Appends elements to the end of the array and returns the length of the modified array.

> var a = [];
> a.push('zig', 'zag', 'zebra','zoo');
4

reverse()

Reverses the elements of the array and returns the modified array.

> var a = [1, 2, 3];
> a.reverse();
[3, 2, 1]
> a;
[3, 2, 1]

shift()

Like pop() but removes the first element, not the last.

> var a = [1, 2, 3];
> a.shift();
1
> a;
[2, 3]

slice(start_index, end_index)

Extracts a piece of the array and returns it as a new array, without modifying the source array.

> var a = ['apple', 'banana','js', 'css', 'orange'];
> a.slice(2,4);
["js", "css"]
> a;
["apple", "banana", "js", "css", "orange"]

sort(callback)

Sorts an array. Optionally accepts a callback function for custom sorting. The callback function receives two array elements as arguments and should return 0 if they are equal, a positive number if the first is greater and a negative number if the second is greater.

An example of a custom sorting function that does a proper numeric sort (since the default is character sorting):

function customSort(a, b) {
 if (a > b) return 1; 
 if (a < b) return -1; 
 return 0;
}
Example use of sort():
> var a = [101, 99, 1, 5];
> a.sort();
 [1, 101, 5, 99]
> a.sort(customSort);
[1, 5, 99, 101]
> [7, 6, 5, 9].sort(customSort);
[5, 6, 7, 9]

splice(start, delete_count, i1, i2, i3,...)

Removes and adds elements at the same time. The first parameter is where to start removing, the second is how many items to remove and the rest of the parameters are new elements to be inserted in the place of the removed ones.

> var a = ['apple', 'banana','js', 'css', 'orange'];
> a.splice(2, 2, 'pear', 'pineapple');
["js", "css"]
> a;
["apple", "banana", "pear", "pineapple", "orange"]

unshift(i1, i2, i3,...)

Like push() but adds the elements at the beginning of the array as opposed to the end. Returns the length of the modified array.

> var a = [1, 2, 3]; 
> a.unshift('one', 'two'); 
5
> a;
["one", "two", 1, 2, 3]

ECMAScript 5 additions to Array

Property/method

Description

Array.isArray(obj)

Tells if an object is an array because typeof is not good enough:

> var arraylike = {0: 101, length: 1};
> typeof arraylike;
"object"
> typeof [];
"object"

Neither is duck-typing (if it walks like a duck and quacks like a duck, it must be a duck):

typeof arraylike.length;
"number"

In ES3 you need the verbose:

> Object.prototype.toString.call([]) ===
 "[object Array]";
true
> Object.prototype.toString.call
   (arraylike) === "[object Array]";
false

In ES5 you get the shorter:

Array.isArray([]);
true
Array.isArray(arraylike);

false

Array.prototype.indexOf(needle, idx)

Searches the array and returns the index of the first match. Returns -1 if there's no match. Optionally can search starting from a specified index.

> var ar = ['one', 'two', 'one', 'two'];
> ar.indexOf('two');
1
> ar.indexOf('two', 2);
3
> ar.indexOf('toot');
-1

Array.prototype.lastIndexOf(needle, idx)

Like indexOf() only searches from the end.

> var ar = ['one', 'two', 'one', 'two'];
> ar.lastIndexOf('two');
3
> ar.lastIndexOf('two', 2);
1
> ar.indexOf('toot');
-1

Array.prototype.forEach(callback, this_obj)

An alternative to a for loop. You specify a callback function that will be called for each element of the array. The callback function gets the arguments: the element, its index and the whole array.

> var log = console.log.bind(console);
> var ar = ['itsy', 'bitsy', 'spider'];
> ar.forEach(log);
itsy      0   ["itsy", "bitsy", "spider"]
bitsy    1   ["itsy", "bitsy", "spider"]
spider  2   ["itsy", "bitsy", "spider"]

Optionally, you can specify a second parameter: the object to be bound to this inside the callback function. So this works too:

> ar.forEach(console.log, console);

Array.prototype.every(callback, this_obj)

You provide a callback function that tests each element of the array. Your callback is given the same arguments as forEach() and it must return true or false depending on whether the given element satisfies your test.

If all elements satisfy your test, every() returns true. If at least one doesn't, every() returns false.

> function hasEye(el, idx, ar) {
    return el.indexOf('i') !== -1;
  }

> ['itsy', 'bitsy', 'spider'].
     every(hasEye);
true
> ['eency', 'weency', 'spider'].
     every(hasEye);
false

If at some point during the loop it becomes clear that the result will be false, the loop stops and returns false.

> [1,2,3].every(function (e) { console.log(e);
    return false;
  });
1

false

Array.prototype.some(callback, this_obj)

Like every() only it returns true if at least one element satisfies your test:

> ['itsy', 'bitsy', 'spider'].
     some(hasEye);
true
> ['eency', 'weency', 'spider'].
     some(hasEye);
true

Array.prototype.filter(callback, this_obj)

Similar to some() and every() but it returns a new array of all elements that satisfy your test:

> ['itsy', 'bitsy', 'spider'].
     filter(hasEye);
["itsy", "bitsy", "spider"]
> ['eency', 'weency', 'spider'].
     filter(hasEye);
["spider"]

Array.prototype.map(callback, this_obj)

Similar to forEach() because it executes a callback for each element, but additionally it constructs a new array with the returned values of your callback and returns it. Let's capitalize all strings in an array:

> function uc(element, index, array) {
    return element.toUpperCase();
  }
> ['eency', 'weency', 'spider'].map(uc);
["EENCY", "WEENCY", "SPIDER"]

Array.prototype.reduce(callback, start)

Executes your callback for each element of the array. Your callback returns a value. This value is passed back to your callback with the next iteration. The whole array is eventually reduced to a single value.

> function sum(res, element, idx, arr) {
    return res + element;
  }
> [1, 2, 3].reduce(sum);
6

Optionally, you can pass a start value which will be used by the first callback call:

> [1, 2, 3].reduce(sum, 100);
106

Array.prototype.reduceRight(callback, start)

Like reduce() but loops from the end of the array.

> function concat(result_so_far, el) {
    return "" + result_so_far + el;
  }

> [1, 2, 3].reduce(concat);
"123"
> [1, 2, 3].reduceRight(concat);
"321"