Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the third parameter thisArg in Array.from method

Array from method can be called with argument items and optional arguments mapfn and thisArg.

Array.from(items, mapfn, thisArg);

The following simple example demonstrate crating new Array using mapfn with multiply logic inside for each items value.

Array.from('123', (item, index) => item * 2); // [2, 4, 6];

What is the third argument? Please give me an example which will showing the case when i should use thisArg.

like image 328
rossoneri Avatar asked Mar 06 '26 12:03

rossoneri


2 Answers

thisArg is Optional

  • Value to use as this when executing mapFn.

a = Array.from('2431', function(item){
  return item*this.multiply;
}, {multiply:2});
console.log(a)
// will return : [4, 8, 6, 2]
and it's identical to:

a = Array.from('2431', (item, index) => item * 2);
console.log(a)
// will return : [4, 8, 6, 2]

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from

like image 64
Unamata Sanatarai Avatar answered Mar 08 '26 01:03

Unamata Sanatarai


The third parameter is

Value to use as this when executing mapFn.

const x = Array.from('123', function(item) {
  console.log("THIS", this);
  return item * 2;
}, {
  test: "valueOfThis"
});

console.log("Result:", x);

ES6 version

const that = { test: "ValueOfThis" };
const x = Array.from('123', (item) => {
  console.log("THIS", that);
  return item * 2;
});

console.log("Result:", x);
like image 43
Weedoze Avatar answered Mar 08 '26 01:03

Weedoze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!