-1

I wrote the following code:

let abcd= Array.from({length:7},(curr,i)=> { console.log(curr,i);  i+1;})
console.log(abcd); // returns [undefined *7]

I can't understand why abcd isn't initialized to 1 to 7?

Eitanos30
  • 1,331
  • 11
  • 19
  • Does this answer your question? [Why doesn't my arrow function return a value?](https://stackoverflow.com/questions/45754957/why-doesnt-my-arrow-function-return-a-value) – Ivar Dec 30 '20 at 15:36

2 Answers2

1

You need to return the value, you are just incrementing it and simply not returning it, hence undefined is added.

const result = Array.from({ length: 7 }, (curr, i) => i + 1 );
console.log(result)
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
  • 1
    lmam, the last language i have learned was kotlin. their the last statement in the block automatically returns the value. thanks! – Eitanos30 Dec 30 '20 at 15:49
1

The value return from the function passed to array.from is added to array. Here you are not returning anything so it automatically return undefined and you get array containing 7 undefined

let abcd= Array.from({length:7},(curr,i)=> {
  console.log(curr,i); 
  return i+1;
})
console.log(abcd); // returns [undefined *7]

A better way for me to create array like this to use spread operator and map()

let abcd = [...Array(7)].map((x, i) => i + 1)
console.log(abcd); // returns [undefined *7]
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • thanks for the great answer. Unfortunately i can approve only one answer, and you were the second one. Thanks again!!! – Eitanos30 Dec 30 '20 at 15:50