Lecture 4: Arrays | JavaScript Full Course

3 min read 4 hours ago
Published on Feb 13, 2025 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial will guide you through the fundamentals of arrays in JavaScript, as covered in Lecture 4 of Shradha Khapra's Full JavaScript Course. Arrays are a crucial data structure in programming, allowing you to store and manipulate collections of data. By the end of this tutorial, you will have a solid understanding of how to create, access, and manipulate arrays in JavaScript.

Step 1: Understanding Arrays

  • An array is a list-like object used to store multiple values in a single variable.
  • Arrays can hold various data types, including numbers, strings, and even other arrays.
  • You can create an array using square brackets [], for example:
    let fruits = ['apple', 'banana', 'cherry'];
    

Step 2: Accessing Array Elements

  • Each element in an array is accessed by its index, which starts at 0.
  • To access an element, use the array name followed by the index in square brackets:
    console.log(fruits[0]); // Outputs: apple
    

Step 3: Looping Over Arrays

  • You can loop through an array using various methods, with the for loop being the most common:
    for (let i = 0; i < fruits.length; i++) {
        console.log(fruits[i]);
    }
    
  • Alternatively, you can use the forEach method for a more concise approach:
    fruits.forEach(function(fruit) {
        console.log(fruit);
    });
    

Step 4: Array Methods

  • JavaScript provides several built-in methods to manipulate arrays. Here are a few common ones:
    • push(): Adds one or more elements to the end of an array.
      fruits.push('orange'); // Adds 'orange' to fruits
      
    • pop(): Removes the last element from an array.
      fruits.pop(); // Removes 'orange'
      
    • shift(): Removes the first element from an array.
      fruits.shift(); // Removes 'apple'
      
    • unshift(): Adds one or more elements to the beginning of an array.
      fruits.unshift('mango'); // Adds 'mango' to the start
      

Step 5: Practice Questions

  • To reinforce your learning, try the following practice questions:
    • Create an array of your favorite movies and print each one using a loop.
    • Use the push() method to add a new movie to your array and print the updated array.
    • Remove an element from the start of your array using shift() and print the result.

Conclusion

In this tutorial, you learned about arrays in JavaScript, how to create and access them, and various methods to manipulate their contents. You should now be comfortable using arrays in your JavaScript projects. As a next step, consider exploring multidimensional arrays or diving deeper into array methods to enhance your programming skills.