From 780d462312f80197c09ceb320b8d53bcb9cc75ef Mon Sep 17 00:00:00 2001 From: samsamson33 Date: Fri, 27 Aug 2021 22:01:27 -0400 Subject: [PATCH] Improve code for initializing array from a function `Array.from()` is, in my opinion at least, clearer in meaning than the spread operator with `Array.prototype.map()`. Also, as it does not create an intermediate array, it appears to be [around twice as fast](https://jsben.ch/phmxK) (on firefox). --- docs/tips/create-arrays.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/tips/create-arrays.md b/docs/tips/create-arrays.md index b677eb234..3ff40cf6f 100644 --- a/docs/tips/create-arrays.md +++ b/docs/tips/create-arrays.md @@ -13,9 +13,9 @@ const foo: string[] = new Array(3).fill(''); console.log(foo); // ['','','']; ``` -If you want to create an array of a predefined length with calls you can use the spread operator: +If you want to create an array of a predefined length with calls you can use `Array.from`: ```ts -const someNumbers = [...new Array(3)].map((_,i) => i * 10); +const someNumbers = Array.from({ length: 3 }, (_, i) => i * 10); console.log(someNumbers); // [0,10,20]; ```