Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Think of Array.of() as the consistent array creator! Unlike new Array() which has weird behavior with numbers, Array.of() always creates an array with the exact items you pass - simple and predictable!
new Array(3) creates empty array with 3 slots, but Array.of(3) creates[3] - one element with value 3!| Code | Result | Explanation |
|---|---|---|
Array.of(3) | [3] | ✅ Array with one element: 3 |
new Array(3) | [empty × 3] | ⚠️ Empty array with 3 slots |
Array.of(1, 2, 3) | [1, 2, 3] | ✅ Array with three elements |
new Array(1, 2, 3) | [1, 2, 3] | ✅ Array with three elements |
[3] | [3] | ✅ Array literal (most common) |
new Array(n) with a single number creates empty slots, not an array with that number!
See how Array.of() always does what you expect
When Array.of() is actually useful
Most common and recommended for creating arrays when you know the values
const arr = [1, 2, 3]; // Simple and clear!When dealing with dynamic single values that might be numbers
const arr = Array.of(userInput); // Safe with any value!Only when you want to create empty array with specific length
const empty = new Array(10); // [empty × 10]When creating ranges or sequences with transformations
const range = Array.from({length: 5}, (_, i) => i);Always creates array with exact arguments passed
Array.of(5) gives [5] not empty array
Perfect for wrapping dynamic values safely
Use [] for literals, Array.of() for dynamic values