Bird
Raised Fist0
DSA Javascriptprogramming

Array Declaration and Initialization in DSA Javascript

Choose your learning style10 modes available
Mental Model
An array is a list that holds items in order, and declaration means creating this list while initialization means filling it with values.
Analogy: Think of an egg carton where each slot holds one egg; declaring the array is like getting the empty carton, and initializing is putting eggs in each slot.
[0] -> [1] -> [2] -> [3] -> null
Each box holds one value, and the arrow shows the order.
Dry Run Walkthrough
Input: Declare an array of size 4 and initialize it with values 10, 20, 30, 40
Goal: Create an array with four slots and fill each slot with the given values
Step 1: Declare an empty array of size 4
[ ] [ ] [ ] [ ]
Why: We need a container with four slots to hold values
Step 2: Assign 10 to index 0
[10] [ ] [ ] [ ]
Why: Fill the first slot with the first value
Step 3: Assign 20 to index 1
[10] [20] [ ] [ ]
Why: Fill the second slot with the second value
Step 4: Assign 30 to index 2
[10] [20] [30] [ ]
Why: Fill the third slot with the third value
Step 5: Assign 40 to index 3
[10] [20] [30] [40]
Why: Fill the fourth slot with the fourth value
Result:
[10] -> [20] -> [30] -> [40] -> null
Annotated Code
DSA Javascript
class ArrayExample {
  constructor(size) {
    this.arr = new Array(size); // declare array with given size
  }

  initialize(values) {
    for (let i = 0; i < Math.min(values.length, this.arr.length); i++) {
      this.arr[i] = values[i]; // assign value to each index
    }
  }

  print() {
    let result = '';
    for (let i = 0; i < this.arr.length; i++) {
      result += this.arr[i] + ' -> ';
    }
    result += 'null';
    console.log(result);
  }
}

// Driver code
const example = new ArrayExample(4); // step 1: declare array of size 4
example.initialize([10, 20, 30, 40]); // steps 2-5: initialize with values
example.print(); // print final array
this.arr = new Array(size); // declare array with given size
create empty array container with fixed size
this.arr[i] = values[i]; // assign value to each index
fill each slot with the corresponding value
result += this.arr[i] + ' -> ';
build string to show array contents in order
OutputSuccess
10 -> 20 -> 30 -> 40 -> null
Complexity Analysis
Time: O(n) because we assign values to each of the n slots once
Space: O(n) because the array holds n elements
vs Alternative: Compared to dynamic resizing, fixed size declaration is simpler and faster for known sizes
Edge Cases
Empty array (size 0)
Creates an empty array with no slots; print shows 'null'
DSA Javascript
this.arr = new Array(size); // declare array with given size
Initialize with fewer values than size
Only first few slots get values; others remain undefined
DSA Javascript
for (let i = 0; i < Math.min(values.length, this.arr.length); i++) { this.arr[i] = values[i]; }
Initialize with more values than size
Only values up to array size are assigned; extra values ignored
DSA Javascript
for (let i = 0; i < Math.min(values.length, this.arr.length); i++) { this.arr[i] = values[i]; }
When to Use This Pattern
When you need to store multiple items in order and access by position, use array declaration and initialization to prepare the container and fill it.
Common Mistakes
Mistake: Forgetting to specify size when declaring array, leading to empty array with length 0
Fix: Always provide size in new Array(size) to allocate slots
Mistake: Assigning values outside array bounds causing undefined behavior
Fix: Ensure initialization loop runs only up to array size
Summary
Creates a fixed-size list and fills it with values in order.
Use when you know how many items you want to store and need quick access by index.
Think of an egg carton: declare the carton first, then put eggs in each slot.

Practice

(1/5)
1. Which of the following is the correct way to declare an empty array in JavaScript?
easy
A. const arr = ();
B. const arr = [];
C. const arr = {};
D. const arr = array();

Solution

  1. Step 1: Understand array declaration syntax

    In JavaScript, arrays are declared using square brackets [].
  2. Step 2: Check each option

    const arr = []; uses square brackets which is correct. Options B and C use parentheses and curly braces which are incorrect for arrays. const arr = array(); uses a function call which is not valid.
  3. Final Answer:

    const arr = []; -> Option B
  4. Quick Check:

    Array declaration uses [] = const arr = []; [OK]
Hint: Arrays use square brackets [] for declaration [OK]
Common Mistakes:
  • Using parentheses () instead of square brackets
  • Using curly braces {} which declare objects
  • Trying to call array() like a function
2. Which of the following is the correct syntax to declare and initialize an array with values 1, 2, and 3?
easy
A. const arr = array[1, 2, 3];
B. const arr = (1, 2, 3);
C. const arr = {1, 2, 3};
D. const arr = [1, 2, 3];

Solution

  1. Step 1: Recall array initialization syntax

    Arrays are initialized with square brackets containing comma-separated values.
  2. Step 2: Evaluate each option

    const arr = [1, 2, 3]; correctly uses square brackets with values. Options B and C use parentheses and curly braces which are invalid. const arr = array[1, 2, 3]; uses incorrect syntax with 'array' keyword.
  3. Final Answer:

    const arr = [1, 2, 3]; -> Option D
  4. Quick Check:

    Array with values uses [] and commas = const arr = [1, 2, 3]; [OK]
Hint: Use square brackets with commas to list values [OK]
Common Mistakes:
  • Using parentheses instead of square brackets
  • Using curly braces which create objects
  • Trying to use 'array' keyword which doesn't exist
3. What will be the output of the following code?
const arr = new Array(3);
console.log(arr);
medium
A. [undefined, undefined, undefined]
B. [0, 0, 0]
C. [empty x 3]
D. SyntaxError

Solution

  1. Step 1: Understand new Array(n) behavior

    Using new Array(3) creates an array with length 3 but no defined values, called a sparse array.
  2. Step 2: Check console output for sparse arrays

    Console shows sparse arrays as [empty x 3], not as undefined or zeros.
  3. Final Answer:

    [empty x 3] -> Option C
  4. Quick Check:

    new Array(3) creates sparse array = [empty x 3] [OK]
Hint: new Array(n) creates empty slots, not undefined values [OK]
Common Mistakes:
  • Assuming new Array(n) fills with zeros
  • Thinking undefined values appear explicitly
  • Expecting a syntax error
4. Identify the error in the following array declaration and fix it:
const arr = new Array[1, 2, 3];
medium
A. Replace square brackets with parentheses: new Array(1, 2, 3);
B. Remove 'new' keyword: Array[1, 2, 3];
C. Use curly braces instead: new Array{1, 2, 3};
D. No error, code is correct

Solution

  1. Step 1: Identify correct syntax for new Array()

    The Array constructor requires parentheses, not square brackets, to pass elements.
  2. Step 2: Fix the syntax

    Change new Array[1, 2, 3] to new Array(1, 2, 3) to correctly create the array.
  3. Final Answer:

    Replace square brackets with parentheses: new Array(1, 2, 3); -> Option A
  4. Quick Check:

    Array constructor uses () not [] = Replace square brackets with parentheses: new Array(1, 2, 3); [OK]
Hint: Array constructor needs parentheses, not square brackets [OK]
Common Mistakes:
  • Using square brackets with new Array
  • Removing 'new' keyword incorrectly
  • Using curly braces which are invalid here
5. How can you programmatically create a 2D array (array of arrays) with 3 rows and 2 columns, all initialized to zero in JavaScript?
hard
A. const arr = Array.from({length: 3}, () => Array(2).fill(0));
B. const arr = Array(3).fill(Array(2).fill(0));
C. const arr = [[0,0],[0,0],[0,0]];
D. All of the above

Solution

  1. Step 1: Understand 2D array initialization

    Using Array.from with a function creates separate inner arrays to avoid shared references.
  2. Step 2: Analyze each option

    const arr = Array(3).fill(Array(2).fill(0)); fills outer array with the same inner array reference, causing changes in one row to affect all. const arr = Array.from({length: 3}, () => Array(2).fill(0)); correctly creates separate inner arrays. const arr = [[0,0],[0,0],[0,0]]; manually creates the array but is less flexible. All of the above is incorrect because only A is fully correct for dynamic initialization.
  3. Final Answer:

    const arr = Array.from({length: 3}, () => Array(2).fill(0)); -> Option A
  4. Quick Check:

    Use Array.from with function for separate inner arrays = const arr = Array.from({length: 3}, () => Array(2).fill(0)); [OK]
Hint: Use Array.from with function to avoid shared inner arrays [OK]
Common Mistakes:
  • Using fill with array causes shared references
  • Manually typing arrays is inflexible
  • Assuming all options are correct
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard