DEV Community

Cover image for Encapsulating console.log with spread operator
Adam K Dean
Adam K Dean

Posted on

1

Encapsulating console.log with spread operator

ES6 or ES2015 contains lots of goodies. One of them, my favourite, is the spread operator. It "allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected."

For example, you can combine two arrays like so:

var start = ['a', 'b', 'c'],
    end = ['d', 'e', 'f'];

var combined = [...start, ...end];

console.log(combined);

// => ['a', 'b', 'c', 'd', 'e', 'f']
Enter fullscreen mode Exit fullscreen mode

What I like even more, is that you can do this with function arguments. Let's say we wanted to wrap console.log so we can do something funky with it. This can easily be done using the spread operator.

var log = function (format, ...args) {
    if (args.length > 0) console.log(format, args);
    else console.log(format);
}

log('test');
log('this is an %s test', 'interpolation');

// => test
// => this is an interpolation test
Enter fullscreen mode Exit fullscreen mode

This changes things. Read more at MDN.

ES7 should also bring object spread operators, so you can do { ...initial, ...change }.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more