Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Object-Oriented JavaScript

You're reading from   Object-Oriented JavaScript Learn everything you need to know about object-oriented JavaScript (OOJS)

Arrow left icon
Product type Paperback
Published in Jan 2017
Publisher Packt
ISBN-13 9781785880568
Length 550 pages
Edition 3rd Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Ved Antani Ved Antani
Author Profile Icon Ved Antani
Ved Antani
Stoyan STEFANOV Stoyan STEFANOV
Author Profile Icon Stoyan STEFANOV
Stoyan STEFANOV
Arrow right icon
View More author details
Toc

Table of Contents (25) Chapters Close

Object-Oriented JavaScript - Third Edition
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface
1. Object-Oriented JavaScript FREE CHAPTER 2. Primitive Data Types, Arrays, Loops, and Conditions 3. Functions 4. Objects 5. ES6 Iterators and Generators 6. Prototype 7. Inheritance 8. Classes and Modules 9. Promises and Proxies 10. The Browser Environment 11. Coding and Design Patterns 12. Testing and Debugging 13. Reactive Programming and React Reserved Words Built-in Functions
Built-in Objects Regular Expressions
Answers to Exercise Questions

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 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

The following are the list of all the elements of an Array:

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

Following are the 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"   

ES6 addition to arrays

Following are the addition to arrays:

Array.from(arrayLike, mapFunc?, thisArg?)

The Array.from() method's basic functionality is to convert two kinds of values to arrays-arrayLike values and Iterable values:

    const arrayLike = { length:
     2, 0: 'a', 1: 'b' };
    const arr =
    Array.from(arrayLike);
    for (const x of arr) {
     // OK, iterable
    console.log(x);
    }
    // Output:
    // a
    // b

Array.of(...items)

Creates an array out of the items passed to the method

    let a = Array.of(
      1,2,3,'foo');
    console.log(a); //[1, 2,
     3, "foo"]

Array.prototype.entries()

Array.prototype.keys()

Array.prototype.values()

The result of these methods is a sequence of values. These methods returns an iterator of keys, values and entries respectively.

    let a = Array.of(1,2,
    3,'foo');
    let k,v,e;
    for (k of a.keys()) {
    console.log(k); //0 1 2 3
    }
    for (v of a.values()) {
    console.log(v); //1 2 
    3 foo
    }
    for (e of a.entries()){
    console.log(e);
    }
    //[[0,1],[1,2],[2,3]
    [3,'foo']]

Array.prototype.find(predicate, thisArg?)

Returns the first array element for which the callback function returns true. If there is no such element, it returns undefined:

    [1, -2, 3].find(x => x < 0)
     //-2

Array.prototype.findIndex(predicate, thisArg?)

Returns the index of the first element for which the callback function returns true. If there is no such element, it returns -1:

    [1, -2, 3].find(x => x < 0)
     //1

Array.prototype.fill(value : any, start=0, end=this.length) : This

It fills an array with the given value:

const arr = ['a', 'b', 'c'];
arr.fill(7)
[ 7, 7, 7 ]
You can specify start and end ranges.
['a', 'b', 'c'].fill(7, 1, 2)
[ 'a', 7, 'c' ]

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $19.99/month. Cancel anytime
Banner background image