CHAPTER - 19
JAVA SCRIPT - WORKING WITH ARRAYS
Overview
Arrays are used to store multiple values in a single variable. They can hold data of
various types and are indexed, allowing easy access to their elements.
Key Concepts
Declaration
Using Array Literals:
let fruits = ["Apple", "Banana", "Cherry"];
Using the Array Constructor:
let fruits = new Array("Apple", "Banana", "Cherry");
Accessing Elements
Access elements using their index (starting from 0).
[Link](fruits[0]); // Outputs: Apple
Adding Elements
- push(): Adds an element to the end of the array.
[Link]("Orange");
- unshift(): Adds an element to the beginning of the array.
[Link]("Mango");
Removing Elements
- pop(): Removes the last element from the array.
[Link](); // Removes Orange
- shift(): Removes the first element from the array.
[Link](); // Removes Mango
Array Methods
- Convert to String:
- toString():
[Link]([Link]());
- join(separator):
[Link]([Link](", "));
- Slice and Concatenate:
- slice(start, end):
let citrus = [Link](1, 3); // Gets elements from index 1 to 2
- concat(array2):
let newFruits = [Link](["Grapes", "Pineapple"]);
forEach() :
● The forEach() method is an array method used to iterate over the elements of an
array. It's part of the Array prototype, which means it can be called directly on any
array.
● The primary purpose of forEach() is to execute a provided function once for each
array element.
Practice Exercises
1. Create an array of your favorite movies. Add and remove movies from the list.
2. Write a function that takes an array of numbers and returns their sum.