Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS arguments.forEach is not a function [duplicate]

So this code works perfectly

var arr = [1, 2, 3, 4];
arr.forEach(function (el) {
    console.log(el);
})

But if i try to do this:

function printArgsInfo() {
    arguments.forEach(function (el) {
        console.log(el);
    });
}
printArgsInfo(2, 3, 2.5, -110.5564, false);

arguments.forEach is not a function

Even though arguments is an array and if Itry to do this with a for in loop it still works.

like image 580
Все Едно Avatar asked Jun 08 '17 11:06

Все Едно


3 Answers

arguments is an array-like object, but not an array:

var doThing = function() {
    console.log(arguments.constructor.name)
    console.log([].constructor.name)
}

doThing("someArgument")


Will return Object for arguments and Array for the empty array [].

ES6 and newer

With ES6, you could use rest parameters ..., as torazaburo suggests.

The rest parameter syntax allows us to represent an indefinite number of arguments as an array.

function printArgsInfo(...args) {
    args.forEach(el => console.log(el));
}

printArgsInfo(2, 3, 2.5, -110.5564, false);

ES5 and older

For ES5 and older, you could borrow the method from Array#forEach and call it with argument as thisArg.

function printArgsInfo() {
    [].forEach.call(arguments, function (el) {
        console.log(el);
    });
}

printArgsInfo(2, 3, 2.5, -110.5564, false);
like image 145
Nina Scholz Avatar answered Nov 16 '22 07:11

Nina Scholz


Per the MDN Docs:

The arguments object is an Array-like object corresponding to the arguments passed to a function.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

So, it is not a true array and does not share the Array object's prototype -- which is where the forEach method is defined.

Interestingly, also from the MDN docs:

You can also use the Array.from() method or the spread operator to convert arguments to a real Array

var args = Array.from(arguments);

So, here is a working example with your code:

function printArgsInfo() {
    var args = Array.from(arguments);

    args.forEach(function (el) {
        console.log(el);
    });
}

printArgsInfo(2, 3, 2.5, -110.5564, false);
like image 5
Levi Mootz Avatar answered Nov 16 '22 06:11

Levi Mootz


Even though arguments is an array

It isn't.

function myFunc() {
    console.log(arguments instanceof Array);
}

myFunc(1,2,3);

The Arguments object is an array-like object. It isn't an array.

like image 4
Quentin Avatar answered Nov 16 '22 06:11

Quentin