Challenge - 5 Problems
Array Initialization Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Array Initialization with Spread Operator
What is the output of the following JavaScript code after array initialization and modification?
DSA Javascript
const arr1 = [1, 2, 3]; const arr2 = [...arr1]; arr2.push(4); console.log(arr1); console.log(arr2);
Attempts:
2 left
💡 Hint
Think about whether arr2 is a copy or a reference to arr1.
✗ Incorrect
The spread operator creates a shallow copy of arr1 into arr2. Modifying arr2 does not affect arr1. So arr1 remains [1, 2, 3], arr2 becomes [1, 2, 3, 4].
❓ Predict Output
intermediateOutput of Array.fill() Method
What is the output of the following JavaScript code using Array.fill()?
DSA Javascript
const arr = new Array(4).fill(0); arr[1] = 5; console.log(arr);
Attempts:
2 left
💡 Hint
Array.fill sets all elements to the same value initially.
✗ Incorrect
Array.fill(0) sets all 4 elements to 0. Then arr[1] is changed to 5. So the array becomes [0, 5, 0, 0].
❓ Predict Output
advancedOutput of Nested Array Initialization and Modification
What is the output of this code involving nested arrays and initialization?
DSA Javascript
const arr = new Array(3).fill([0, 0]); arr[0][0] = 1; console.log(arr);
Attempts:
2 left
💡 Hint
Consider whether the inner arrays are shared references or separate copies.
✗ Incorrect
Using fill with an array fills all positions with the same reference. Changing arr[0][0] changes all inner arrays at index 0.
🧠 Conceptual
advancedUnderstanding Array Initialization with map()
Which code snippet correctly initializes an array of length 5 with values 0 to 4?
Attempts:
2 left
💡 Hint
Remember that map() on empty slots does not run.
✗ Incorrect
Array.from with length and map function correctly creates [0,1,2,3,4]. map() on empty slots does not execute callback.
🔧 Debug
expertIdentify the Error in Array Initialization
What error does the following code produce?
DSA Javascript
const arr = Array(3).fill([]); arr[0].push(1); console.log(arr);
Attempts:
2 left
💡 Hint
Think about what fill([]) does with references.
✗ Incorrect
fill([]) fills all positions with the same array reference. Pushing to arr[0] affects all elements.
