Skip to content

Instantly share code, notes, and snippets.

@Rplus
Created February 6, 2017 18:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Rplus/ff0237d7b518afb24f5652eaa53097c8 to your computer and use it in GitHub Desktop.
Save Rplus/ff0237d7b518afb24f5652eaa53097c8 to your computer and use it in GitHub Desktop.
6 Great Uses of the Spread Operator, via: https://davidwalsh.name/spread-operator

Calling Functions without Apply

function doStuff (x, y, z) { }
var args = [0, 1, 2];
doStuff(...args);
function doStuff(x, y, z) {}
var args = [0, 1, 2];
doStuff.apply(undefined, args);

Combine Arrays

var arr1 = ['two', 'three'];
var arr2 = ['one', ...arr1, 'four', 'five'];
var arr1 = ['two', 'three'];
var arr2 = ['one'].concat(arr1, ['four', 'five']);

arr1.push(...arr2) // Adds arr2 items to end of array
arr1.unshift(...arr2) //Adds arr2 items to beginning of array
arr1.push.apply(arr1, arr2);
arr1.unshift.apply(arr1, arr2);

Copying Arrays

var arr = [1, 2, 3];
var arr2 = [...arr]; // like arr.slice()
arr2.push(4);
var arr = [1, 2, 3];
var arr2 = [].concat(arr);
arr2.push(4);

Convert arguments or NodeList to Array

[...document.querySelectorAll('div')];
[].concat(document.querySelectorAll('div'));

Using Math Functions

let numbers = [9, 4, 7, 1];
Math.min(...numbers); // 1
var numbers = [9, 4, 7, 1];
(_Math = Math).min.apply(_Math, numbers);

Destructuring Fun

let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
console.log(x); // 1
console.log(y); // 2
console.log(z); // { a: 3, b: 4 }
var _Math;
function _objectWithoutProperties(obj, keys) {
    var target = {};
    for (var i in obj) {
        if (window.CP.shouldStopExecution(1)) {
            break;
        }
        if (keys.indexOf(i) >= 0)
            continue;
        if (!Object.prototype.hasOwnProperty.call(obj, i))
            continue;
        target[i] = obj[i];
    }
    window.CP.exitedLoop(1);
    return target;
}
var _x$y$a$b = {x: 1, y: 2, a: 3, b: 4};
var x = _x$y$a$b.x;
var y = _x$y$a$b.y;
var z = _objectWithoutProperties(_x$y$a$b, ['x', 'y']);
console.log(x);
console.log(y);
console.log(z);
@Rplus
Copy link
Author

Rplus commented Feb 9, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment