Using Prototypes with Arrays

Video

JavaScript Notes

JavaScript
    let log = console.log;
    let names = ['Sterling', 'Pam', 'Cyril', 'Lana', 'Hallory', 'Cheryl'];

    // use the built-in Array.sort( ) method 
    let sorted = names.sort( ); 
    console.log(sorted); 
    console.log(names);

    // Create a new Array method called "shuffle" on the Array prototype object 
    Array.prototype.shuffle = function ( ) {
        let len = this.length ;  for (let i = 0; i<len; i++) {
            let temp = "".concat(this[i]);	// this will take a new value and not use the original array 
            let pos = Math.floor(Math.random( ) * len);
            let other = "".concat(this[pos]);
            this[i] = other; 
            this[pos] = temp;
        }
        return this;
    }
    let shuffled = names.shuffle( ).shuffle( ).shuffle( );	// these can be chained 
    log(shuffled);