0

Please can someone explain what this command does in javascript or how this language feature is called? Why is there forEach on empty array?

[].forEach.call(document.querySelectorAll('.mdc-text-field'), function (el) {
  new MDCTextField(el);
});

I am new to frontend technologies.

Martin Staufcik
  • 8,295
  • 4
  • 44
  • 63
  • 3
    Please refer to this reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call - The code you provide is a hack that is unecessary. It passes the first argument to `call()` to the `forEach()` method of the array. The array is empty, but the first argument contains a DOM NodeList that can act like an array. So this basically uses the `forEach()` method to iterate over the DOM elements. It isn't necessary because the DOM NodeList object has a forEach method. – Randy Casburn Dec 13 '20 at 14:07
  • @RandyCasburn "*It isn't necessary because the DOM NodeList object has a forEach method*"–That code is likely legacy. `NodeList#forEach` is not supported in Internet Explorer and other older browsers. – str Dec 13 '20 at 14:09
  • Here is the reference to the [DOM NodeList API](https://developer.mozilla.org/en-US/docs/Web/API/NodeList) - There you will find it has a `forEach()` method so the hack is not required. All that is needed is this: `document.querySelectorAll(...).forEach(...)` – Randy Casburn Dec 13 '20 at 14:09
  • Yes, @str is correct - if this is legacy code use for IE, then there is no choice but to use this hack. – Randy Casburn Dec 13 '20 at 14:10
  • `[].forEach` is a shorthand for `Array.prototype.forEach` – Thomas Dec 13 '20 at 14:32

0 Answers0