1

I am trying to perform a function on my arguments, which is variable length. I can't seem to run any function on my arguments array, including sort.

function findKeyFromNotes()
    {
         var notes = arguments.slice(); 
         return notes;  
    }

I am getting this error:

TypeError: arguments.slice is not a function

Thanks, Nakul

10
  • How are you calling findKeyFromNotes? Commented Nov 5, 2019 at 0:29
  • 1
    @ScottHunter it doesn't matter, the arguments object doesn't have a .slice() method. Commented Nov 5, 2019 at 0:29
  • var realArray = [].slice.call(arguments); Commented Nov 5, 2019 at 0:44
  • @StackSlave that's a very common pattern, but it's not the best idea because leaking the arguments object makes it basically impossible to optimize the function (because arguments does weird things). Commented Nov 5, 2019 at 0:57
  • 1
    @Pointy Yes, that happens in sloppy mode only. Commented Nov 5, 2019 at 9:37

1 Answer 1

1

In modern JavaScript, you can use the spread syntax to collect all arguments into a single array value:

function findKeyFromNotes(... notes) {
  // notes will be an array
}

In "traditional" JavaScript the best thing to do would be:

function findKeyFromNotes() {
  var notes = [];
  for (var i = 0; i < arguments.length; ++i) notes[i] = arguments[i];
  // now notes is a plain array
}
Sign up to request clarification or add additional context in comments.

2 Comments

The common use of .slice() to convert arguments to an array is kind-of a bad idea because it seriously impedes JIT optimization.
My comment does not apply to "strict" mode code however.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.