Search our website

From the blog

Posts by tag

Currently displaying: javascript

Developer
ugrc social card

Quick JavaScript Tip: The Arguments Object (2 min)

Recently, as I was slowly working my way through Rebecca Murphy's [https://rmurphey.com/] excellent js-assessment test suite [https://github.com/rmurphey/js-assessment], I ran into a problem that was quite vexing. I was creating a function that was to take an arbitrary number of arguments and combine them with an existing array [https://github.com/rmurphey/js-assessment/blob/master/tests/app/functions.js#L109-119]. I thought that this would be as trivial as using the concat method on the existing array and passing in the arguments object. However, as you can see below, it didn't work. See the Pen Arguments Concat Method [https://codepen.io/stdavis/pen/BPVWdQ/] by Scott Davis (@stdavis [https://codepen.io/stdavis]) on CodePen [https://codepen.io]. For a while I thought that I must be using the concat method incorrectly. I tested it using the terminal again and again with no problems. Finally I recalled a recent issue [https://us6.campaign-archive1.com/?u=2cc20705b76fa66ab84a6634f&id=c8f1074cb2] from A Drip of JavaScript that talked about the arguments object. I remembered that Joshua said that the arguments object "isn't exactly an array, [but rather an] object that acts like an array." This means that you can't use it exactly like an array. An easy fix for the situation was to bind a call to the slice method on an empty array to the arguments object which converts it to a true array object like so: See the Pen Arguments Slice [https://codepen.io/stdavis/pen/xJzqPB/] by Scott Davis (@stdavis [https://codepen.io/stdavis]) on CodePen [https://codepen.io]. Hopefully this will save you some time in the future. Scott [https://twitter.com/SThomasDavis]