Pass By Reference

Video

JavaScript Notes

JavaScript
    // JavaScript Passes by REFERENCE, on NON-PRIMITIVE values (i.e. Objects!)
    // Not by value (copy) - which is does only for PRIMITIVE values
    /** JSON.parse(JSON.stringify(obj))
    * best if small object (under 1Kb)
    MessageChannel onmessage, postMessage communication 
    History API history.replaceState( ) and history.state Notification API
    **/
    
    let log = console.log; 
    let x = a;
    let y = a;
    let z = x;	// this is not a copy of x, it ‘is’ x!
    z = "b"	    // changes both the value of x and z!
    
    let names = ['Bob', 'Louise', 'Tina', 'Linda', 'Gene'];
    
    let f = function(arr) {
        let a = Array.from(arr);	// this creates a brand new array
        let r = [ ].concat(arr);	// this creates a brand new array
        arr.push('Mort');
        log(arr);	// this will have Mort!
        log(names);	// this will have Mort!
        log(a);	    // this was created before Mort was added
        log(r);	    // this was created before Mort was added
    }
    f(names);
    
    let archer = {
        characters: ['Sterling', 'Pam', 'Lana', 'Mallory'],
        info: {inner:true, nums:[1,2,3]}
    }
    
    let g = (obj) => {
        let o = Object.assign({ }, obj);	              // Assign only creates a shallow copy. Copies properties over, but still points to / references to the arrays & objects inside of archer! 
        obj.characters = ['Slater', 'Sterling', 'Lana'];  // The equal sign, after the property changes the original reference and creates a new object, so in the next step, only obj, and its reference, archer are affected! 
        obj.characters.push('Cheryl');                    // ‘o’ still points to [‘Sterling’, ‘Pam’, ‘Lana’, etc..] 
        
        obj.info.inner = false;                           // changes o, obj, and archer
        obj.info.nums = [4,5,6];                          // changes o, obj, and archer
        log('OBJ', obj);
        log('ARCHER', archer);
        log('O', o);

        return o;
    }
    let newObj = g(archer);             // newObj equals to the return value 'o'

    newObj.characters.push('Cyril');	// will be added to the array in NewOBJ only 
    newObj.info.nums.push(8);	        // will be added to arrays in NewOBJ, ARCHER, OBJ, & O 

    log('NEWOBJ', newObj);
    log('ARCHER', archer);