0

I have the following basic js function:

function copy_array(arr) {
    // copy array and return existing array
    const cp = [];
    for(let i=0; i < arr.length; i++)
        cp[i] = arr[i];
    return cp;
}

Is it possible to convert this into an arrow function, for example:

const copy_array2 = (arr) => {
   // ?
}
David542
  • 104,438
  • 178
  • 489
  • 842
  • 3
    Yes, you can put the same code within your regular function into your arrow function – Nick Parsons Oct 08 '21 at 23:13
  • 2
    Why do you think it would be any different? – Barmar Oct 08 '21 at 23:14
  • Arrow functions are missing a few features from regular functions (such as `arguments`), but you don't use any of them. – Barmar Oct 08 '21 at 23:15
  • @NickParsons I see. So is there any advantage of having the above as an Arrow function, or in the above case it's irrelevant. – David542 Oct 08 '21 at 23:16
  • 2
    @David542 for the above example I can't think of any advantages of using an arrow function, but if you had different code within your function then it might be more appropriate to use an arrow function (you can see: [Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?](https://stackoverflow.com/q/34361379) for more details about the differences). – Nick Parsons Oct 08 '21 at 23:18
  • voting to close as dup. Not helpful or anything new for future users. – Always Helping Oct 08 '21 at 23:33
  • `const copyArray2 = arr => arr.map(x=>x);` – Mister Jojo Oct 08 '21 at 23:42

1 Answers1

1

Simply:

const copy_array2 = (arr) => {
    const cp = [];
    for(let i=0; i < arr.length; i++)
        cp[i] = arr[i];
    return cp;

}

const arr = [1, 2, 3]
const copy = copy_array2(arr)

arr[0] = 5

console.log(copy)
Spectric
  • 30,714
  • 6
  • 20
  • 43