Getting arguments passed to an ES6 arrow function using arguments variable

Justin picture Justin · Feb 12, 2016 · Viewed 16.5k times · Source

I understand how arrow functions work in ES6, and the lexical this, but I was wondering if anyone knows of a way to get the arguments passed to an arrow function?

In ES5, you can simply do:

function foo( bar, baz ){
    console.log('Args:', arguments.join(', '))
}

However, in ES6, if you use an arrow function, like so:

const foo = ( bar, baz ) => {
    console.log('Args:', arguments.join(', '))
}

The arguments variable returns an object, which is nothing close to the parameters.

So, I was wondering if anyone has a way to get the arguments passed to an arrow function?


Edit

I guess maybe I should give some info on what I'm trying to accomplish, maybe if the above isn't possible, someone has a better idea.

Basically, I'm adding a IIEF to the BluebirdJS asCallback method, which will determine if there was actually a callback provided, if not, it returns the promise.

Heres a working example in ES5:

var _ = require('lodash')
var Promise = require('bluebird')

function testFunc( foo, callback ) {
    return new Promise( function ( res, rej ){
        res('You Said: ' + (_.isString( foo ) ? foo : 'NOTHING') )
    })
        .asCallback((function ( args ) {
            return _.findLast(args, function(a) {
                return _.isFunction( a )
            })
        })( arguments ))
}


testFunc('test', function( err, data ) {
    if( ! _.isEmpty( err ) )
        console.log('ERR:', err)
    else
        console.log('DATA: ', data)
})
// DATA:  You Said: test

testFunc(function( err, data ) {
    if( ! _.isEmpty( err ) )
        console.log('ERR:', err)
    else
        console.log('DATA: ', data)
})
// DATA:  You Said: NOTHING

So that works fine if I use all ES5 functions, and I don't mind using them for the IIEF, or inside it if needed. But this hinges on the arguments variable inside a function that I don't really want to use as an ES5 function, id rather stick to ES6 Arrow functions. So if theres some ES6 way to get arguments in an ES6 arrow function, that would be perfect!

Answer

Vicky Gonsalves picture Vicky Gonsalves · Feb 12, 2016

Arrow functions don't have their own this and arguments. Having said that, you can still get all arguments passed into the arrow functions using Rest parameters AKA spread operator:
Ref: https://strongloop.com/strongblog/an-introduction-to-javascript-es6-arrow-functions/

function message(msg) {
  const foo = (...args) => console.log(args[0]);
  foo(`Message: ${msg}`);
}

message('Hello World'); // Message: Hello World