Getting arguments passed to an ES6 arrow function using arguments variable [duplicate]
Asked Answered
C

1

28

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!

Corroborant answered 12/2, 2016 at 16:59 Comment(5)
Arrow functions don't expose arguments.Uncrowned
The question is whether we can do both destructuring ({a, b}) => ( a + b ) and grab the arguments at the same time. Something like (...args = {a, b}) => ( a + b + f(args) ). And it is by no means duplicated.Sf
This question is not at all the duplicate, But yet the answer could have been const foo = (...args) => { console.log('Args:', args.join(', ')) } This is your way to go with fat arrow functionPuccoon
There is a section near the bottom of the accepted answer for the other question, called "Variadic Functions", which answers this question; i.e use this: foo = (...args) => {}. It is hard to find in the context of the other question.Inconsumable
I'm always disappointed in SO when I see a question inappropriately closed like this. 1.) Once again, they missed the question actually being asked - even though @AdrianSilvescu explained it (then two people commented after Adrian that still didn't take the time to understand). 2.) Either way, they're completely different questions. 3.) Many people with this question already know the answer to the second (which OP obviously did), and wouldn't use those search words or think to look at that question. 4.) Even if it does have the answer, it shouldn't. It's outside the scope of that question!Ninety
O
33

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
Ollieollis answered 12/2, 2016 at 17:17 Comment(11)
The spread operator is actually kinda off topic. And the above uses an arrow function inside of an ES5 type function, so that doesn't accomplish what I was looking for. If you can get that message function itself to be an arrow function, then that would suffice.Corroborant
Can you link to the source you are citing? Or is this actually not a citation?Club
@Justin: The point it that you can use the rest parameter to access all arguments passed to an arrow function. The context of the arrow function doesn't matter.Club
Sure... strongloop.com/strongblog/…Ollieollis
FWIW, the spread "operator" and the rest parameter are two different things.Club
The rest parameter is used in function declarations: function foo(...rest) {} . The spread "operator" (it's not an operator) is use to spread/explode an iterable into an array or function call: [a,b,c, ...arr], foo(1,2,...arr).Club
@FelixKling Thanks for clarification.Ollieollis
It only works if you transpiled it to ES5. Otherwise, it throws an error. Just plain old arrow functions work fine when they arent transpiled, was hoping to be able to use something in thereCorroborant
What is this a duplicate of? Incidentally the example rest spread operater is not particularly useful. I think this is better: myFat = ({x,y,z}) =>{ const {...args} = {x,y,z}; }Cavit
Looks really ugly, I think we should avoid thisPiscine
@SteveTomlin 's comment was very useful and necessary ( for me ) to understand how to find the solutionHobie

© 2022 - 2024 — McMap. All rights reserved.