Convert arguments to Array
The arguments object thats automatically available within functions can be a source of confusion for some people; it's kind of an array but it's kinda not. JavaScript is awesome in that you can pass any number of arguments to a function, and oftentimes developers need to iterate over every argument provided. The arguments object doesn't have a forEach method, but using a quick JavaScript technique, you can convert arguments to an array:
function myFn(/* any number of arguments */) {
var args = Array.prototype.slice.call(arguments);
// or [].slice.call(arguments)
args.forEach(function(arg) {
// do something with args here
});
}
Much like converting a NodeList to an array, Array's slice method takes the arguments object and converts it to a true array, allowing for forEach, map, and traditional array iteration. Keep that trick up your sleeve for future development.
![Write Better JavaScript with Promises]()
You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...
![Creating Scrolling Parallax Effects with CSS]()
Introduction
For quite a long time now websites with the so called "parallax" effect have been really popular.
In case you have not heard of this effect, it basically includes different layers of images that are moving in different directions or with different speed. This leads to a...
![Checkbox Filtering Using MooTools ElementFilter]()
When I first wrote MooTools ElementFilter, I didn't think much of it. Fast forward eight months later and I've realized I've used the plugin a billion times. Hell, even one of the "big 3" search engines is using it for their maps application.
![CSS Background Animations]()
Background animations are an awesome touch when used correctly. In the past, I used MooTools to animate a background position. Luckily these days CSS animations are widely supported enough to rely on them to take over JavaScript-based animation tasks. The following simple CSS snippet animates...
If you’re using Firefox, or in the future when other browsers support ES6, you can do it more elegantly:
function myFn(...args) { /* code */ }In case you are using Mootools,
Array.fromdoes the job, isn’t it ?Why not it:
You can do that but be aware if you do something like:
function x(){ return Array.apply(null, arguments); }; x(10); //=> it will return empty array with a length of 10 instead of [10]Cool trick, but why even
typeof argumentsreturnsobject?We have a new method,
Array.from(arguments)