15.5 Array Best Practices (15 mins)

  1. When to Use Arrays:

    • Arrays are ideal when you need to store multiple values that are related to each other, such as:

      • Lists of items (e.g., names, numbers, objects).

      • Collections of data that can be easily accessed by index (e.g., students in a class, product inventory).

    • Arrays are particularly useful when:

      • Data is ordered: When you need to preserve the order of elements (like a list of recent events or tasks).

      • Iterating over data: When you need to loop through the data to perform operations like filtering, sorting, or calculating totals.

    • Example:

      let shoppingList = ["Milk", "Eggs", "Bread"];
  2. Best Practices for Using Arrays:

    • Use Descriptive Names:

      • Name your arrays clearly and meaningfully based on the data they contain.

      • Example:

        let studentNames = ["Alice", "Bob", "Charlie"];  // Clear and descriptive
    • Avoid Sparse Arrays:

      • Sparse arrays are arrays with "holes" where some indices are missing. This can cause unexpected results in loops and operations.

      • Example (Avoid):

        let numbers = [1, , 3];  // Index 1 is missing (avoid this)
    • Use Array Methods Efficiently:

      • Use built-in methods like map(), filter(), and reduce() to perform common operations more efficiently than manual loops.

      • Example:

        let numbers = [1, 2, 3, 4];
        let doubled = numbers.map((num) => num * 2);  // Doubles each number in the array
        console.log(doubled);  // Outputs: [2, 4, 6, 8]
    • Optimize Performance for Large Arrays:

      • In large applications, handling large datasets in arrays can impact performance. Here are some optimization tips:

        • Avoid Frequent Modifications: Adding/removing elements frequently can cause performance issues. Instead, batch changes or use more efficient data structures like linked lists if necessary.

        • Use for loops for Performance: While methods like forEach() and map() are convenient, a traditional for loop can be more efficient for very large arrays.

        • Avoid Nested Loops: If possible, avoid nested loops that iterate over large arrays multiple times, as this increases the time complexity.

  3. Choosing the Right Data Structure:

    • While arrays are versatile, sometimes other data structures (e.g., objects, maps, sets) may be more appropriate depending on the use case.

    • Example:

      • Use arrays for ordered data like lists.

      • Use objects when you need key-value pairs.

      • Use sets when you need unique values only.

      // A Set will only store unique values
      let uniqueNumbers = new Set([1, 2, 2, 3]);  

Student Activity (15 mins):

Objective: Students will practice applying best practices for arrays by creating efficient arrays and using optimized methods to handle data.


Step-by-Step Activity:

  1. Create an HTML file (e.g., array_best_practices.html) and write JavaScript code that demonstrates best practices for using arrays efficiently. Note: The three dots (...) in JavaScript is known as the spread operator, and it's used to make shallow copies of JavaScript objects.

  2. Three Dots (...) Operator Syntax in JavaScript

// Three dots (...) usages - Inserting the Elements of One Array Into Another
let desserts = ['cake', 'cookie', 'donut'];
let desserts1 = ['icecream', 'flan', 'frozen yoghurt', ...desserts];
console.log(desserts);
//Appending baked_desserts after flan
let desserts2 = ['icecream', 'flan', ...desserts, 'frozen yoghurt'];
console.log(desserts2);
// output
[ 'cake', 'cookie', 'donut' ]
[ 'icecream', 'flan', 'cake', 'cookie', 'donut', 'frozen yoghurt' ]
// Three dots (...) usages - Array to Arguments
function multiply(number1, number2, number3) {
  console.log(number1 * number2 * number3);
}
let numbers = [1,2,3];
multiply(...numbers);//output: 6
multiply(numbers); //output: NaN
  1. Example Code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Array Best Practices</title>
    </head>
    <body>
      <h1>Check the Console for Array Outputs</h1>
    
      <script>
        // 1. Use descriptive names for arrays
        let fruitBasket = ["Apple", "Banana", "Orange"];
        console.log("Fruit Basket: " + fruitBasket);
    
        // 2. Avoid sparse arrays (bad practice)
        let numbers = [1, , 3];  // Index 1 is missing (sparse array)
        console.log("Sparse Array (Avoid): " + numbers);
    
        // 3. Use array methods efficiently (map, filter, reduce)
        let grades = [85, 90, 78, 92, 88];
        let passedGrades = grades.filter((grade) => grade >= 80);  // Filter passing grades
        console.log("Passing Grades: " + passedGrades);  // Outputs: [85, 90, 92, 88]
    
        // 4. Optimize for large arrays
        let largeArray = [];
        for (let i = 0; i < 1000000; i++) {
          largeArray.push(i);  // Adding elements in a loop (but avoid doing this in real-time applications)
        }
        console.log("Large array created with 1 million elements");
    
        // 5. Use sets for unique values
        let uniqueSet = new Set([1, 2, 2, 3, 3, 4]);  // Will only store unique numbers
        console.log("Unique Set: " + [...uniqueSet]);  // Converts Set back to array and displays unique values
      </script>
    </body>
    </html>

Explanation:

  • Descriptive Names: Students will see how to name arrays meaningfully based on the data they contain.

  • Avoid Sparse Arrays: A warning about sparse arrays and how they can cause unexpected behavior.

  • Efficient Use of Array Methods: Demonstrating map(), filter(), and other methods to optimize array operations.

  • Handling Large Arrays: Show how to avoid frequent modifications to large arrays and optimize performance.

  • Using Set for Unique Values: Introduce Set as an efficient way to store unique elements in JavaScript.


Run the file in a browser:

  • Open the HTML file in a browser and use Developer Tools (F12 or right-click and select Inspect > Console) to view the output of the array practices.


Challenge:

  1. Modify the Code:

    • Write a function that takes an array of numbers and returns only the unique numbers in the array by converting it to a Set.

    Example:

    function getUniqueNumbers(arr) {
      return [...new Set(arr)];
    }
    
    let uniqueNumbers = getUniqueNumbers([1, 2, 3, 3, 4, 5, 5]);
    console.log("Unique Numbers: " + uniqueNumbers);  // Outputs: [1, 2, 3, 4, 5]
  2. Extra Challenge:

    • Create a function that takes a large array of numbers and calculates the average of all the values using reduce().

    Example:

    function calculateAverage(arr) {
      let sum = arr.reduce((total, num) => total + num, 0);
      return sum / arr.length;
    }
    
    let avg = calculateAverage([10, 20, 30, 40, 50]);
    console.log("Average: " + avg);  // Outputs: 30

Activity Follow-up Questions:

  1. Why is it important to avoid sparse arrays?

  2. How can using filter() and reduce() optimize operations on arrays?

  3. In what scenarios would using a Set be more beneficial than using an array?


Expected Outcome:

Students will:

  • Understand the best practices for using arrays, such as naming conventions, avoiding sparse arrays, and using built-in methods for efficiency.

  • Learn how to optimize array performance in larger applications and handle large data sets effectively.

  • Gain experience using Set for unique values and learn when to choose other data structures over arrays.

Last updated