ES6 Default, Rest, and Spread

node v0.12.18
version: 1.0.0
endpointsharetweet
ES6 adds default and rest parameters to your functions. Default parameters can replace the old method of having to check whether arguments were passed in, then assigning them if they're missing:
var production = true; // By default, use log. Before we'd have to check argument.length // or whether type was undefined to get the same effect: function DEV_LOG(string, type = "log") { if (!production || type === "error") console[type](string); } // Won't print since in production. DEV_LOG("Status Log"); // Will print since its an error. DEV_LOG("Error Log", "error");
With rest parameters, you can easily treat multiple parameters as if they were part of a list:
function hasAny(array, ...needles) { return needles.some(aNeedle => array.indexOf(aNeedle) !== -1) } hasAny([1,2,3,4,5,6,7], 101, 9, 7)
Spread allows you to do the opposite. Many functions expect all the items to be given as parameters, not one big list (such as Math.max). Spread allows us to "unwind" a list into parameters:
var numbers = [1,2,3,4,5,6,7,8,9,10]; Math.max(...numbers);
Loading…

2 comments

  • posted 6 months ago by 65374c7ea7ec220008a7bdfb
    I
  • posted 5 months ago by elmonjo
    I want to go lovely

sign in to comment