Skip to content

Commit e95c6c1

Browse files
committed
Added array creation tip
1 parent d267bbe commit e95c6c1

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

README.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ Useful JavaScript Tips & Tricks
88

99
- [Console Table - Display tabular data as a table](#console-table).
1010
- [Console Log With Variable Name](#console-log-with-variable-name).
11+
- [Short code to create array of `n` length from `0` to `n-1`](short-code-to-create-array).
1112

1213
<br>
1314

@@ -69,6 +70,46 @@ Now you can easily say that `completed` is indeed `true` here.
6970

7071
Reference: [Wes Bos's 2016 Tweet](https://twitter.com/wesbos/status/798579690575462400)
7172

73+
## Short Code To Create Array
74+
75+
Sometimes we might need to create an array of `n` length like `[0, 1, 2, ..., n-1]`. We can do this easily using ES6 [Spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) like:
76+
77+
```js
78+
[...Array(n).keys()];
79+
```
80+
81+
This is a general version. If you need an array of length `10`, then you can set it like:
82+
83+
```js
84+
[...Array(10).keys()];
85+
// Result => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
86+
```
87+
88+
### Brief explanation
89+
90+
1. `Array(10)` create an empty array of length `10` like `[,,,...]` where value of any index from 0-9 is `undefined`.
91+
2. `Array(10).keys()` this returns a new **Array Iterator** object that contains the keys for each index in the array.
92+
93+
```js
94+
var array1 = Array(3);
95+
var iterator = array1.keys();
96+
97+
for (let key of iterator) {
98+
console.log(key); // expected output: 0 1 2
99+
}
100+
```
101+
102+
3. `[...Array(10).keys()]` this creates a new, shallow-copied `Array` instance from `Array(10).keys()` iterable object.
103+
104+
### Bonus Trick
105+
106+
If you want the array to start from `1` and end with `n` here like `[1, 2, 3, ..., n]` instead of `[0, 1, 2, ..., n-1]`, then you can do like this:
107+
108+
```js
109+
[...Array(10)].map((v, i) => ++i);
110+
// Result => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
111+
```
112+
72113
## Next Tip
73114

74115
Coming soon...

0 commit comments

Comments
 (0)