Array In JavaScript


An Array in JavaScript is define as a data structure used to stored multiple value of different datatypes, means array in javascript can hold different datatypes in single variable.

Indexing of Array Element starts from 0 (ZERO).

2 Different ways to create of Array In JavaScript:

  • Creating Literal array:

// Creating an Empty Array
let arr = [];
console.log(arr);

// Creating an Array and Initializing with Values
let arr= [10, "sahiba", 32];
console.log(arr);

  • Create using new Keyword (Constructor):

    // Creating and Initializing an array with values
let arr = new Array(1, "sahiba", true);

console.log(arr);


Operations to perform on Array:

  • Length of an array:


let arr = [1, "sahiba", true];

console.log(arr.length);

  • Get First Value of an array:

let arr = [1, "sahiba", true];

console.log(arr[0]);

  • Get Last Value of an array:

let arr = [1, "sahiba", true];

console.log(arr[arr.length-1]);

  • Print all values of an array:

Using loop: 

let arr = [1, "sahiba", true];

for(let i=0; i<arr.length; i++)
{
console.log(arr[i]);
}

Using ForEach Method: 

let arr=[10,20,"sahiba"];

arr.forEach((item) => {
console.log(item);
});

  • Modify Value of an array:

let arr = [1, "sahiba", "khurana"];

arr[0] = "Ms";
console.log(arr);

  • Increase and Decrease the Array Length:

let arr = [1, "sahiba", "khurana"];

//Increase the array length

arr.length=5;
console.log("After increasing length=", arr.length);

//Decrease the array length

arr.length=2;
console.log("After decreasing length=", arr.length);

  • Conversion of an Array to String:

let arr = [1, "sahiba", "khurana"];

//Convert array to String

console.log(arr.toString());

      forEach() Method in Array:

      The forEach() method in JavaScript is used to iterate over elements in an array. It executes a provided function once for each array element in order. It is a simpler and more readable way to perform operations on each element of an array compared to using traditional for or while loops.

      Syntax:

      array.forEach(callback(currentValue, index, array), thisArg);

      Parameters:

      1. callback: A function to execute on each element in the array. It takes three arguments:

        • currentValue: The current element being processed.
        • index (optional): The index of the current element.
        • array (optional): The array forEach() was called upon.
      2. thisArg (optional): A value to use as this when executing the callback function.


      Key Characteristics:

      1. Non-returning: forEach() doesn’t return a new array; it always returns undefined. Use it when you don't need a new array as the result of the operation.
      2. Non-breaking: You cannot use break or continue to terminate the loop. If you need to break the iteration, consider using a for loop or a for...of loop instead.
      3. Mutability: It can be used to mutate the original array if necessary but doesn't create a new array.

      Example 1: Basic Usage


      const fruits = ['apple', 'banana', 'cherry']; fruits.forEach((fruit) => { console.log(fruit); });

      Output:
      apple banana
      cherry

      Example 2: Using Index


      const fruits = ['apple', 'banana', 'cherry']; fruits.forEach((fruit, index) => { console.log(`Index ${index}: ${fruit}`); });
      Output:
      Index 0: apple
      Index 1: banana
      Index 2: cherry



      Example 3: Accessing the Array


      const numbers = [1, 2, 3, 4]; numbers.forEach((num, index, array) => { console.log(`Number: ${num}, Array Length: ${array.length}`); });
      Output:
      Number: 1, Array Length: 4 Number: 2, Array Length: 4 Number: 3, Array Length: 4 Number: 4, Array Length: 4

      Example 4: Modifying Array Elements


      let numbers = [1, 2, 3]; numbers.forEach((num, index, arr) => { arr[index] = num * 2; }); console.log(numbers);

      // Output: [2, 4, 6]

      Example 5: Using thisArg


      const obj = { multiplier: 2, }; const numbers = [1, 2, 3]; numbers.forEach(function (num) { console.log(num * this.multiplier); }, obj);

      // Output:
      2 4
      6


      Common Use Cases:

      1. Logging or Debugging: Print each element of an array.

      2. Performing Operations: Perform a specific operation on each element, like summing up values or applying a transformation.

      3. Manipulating DOM Elements: Apply changes to multiple DOM elements.

      4. Side Effects: Run a function on each array element without returning a result.


      Limitations:

      1. Does Not Support break/continue: Use a for loop if breaking the loop is necessary.
      2. Not Chainable: Since forEach() returns undefined, it cannot be chained with other array methods.
      3. Synchronous Execution: It runs synchronously, meaning it waits for each callback to complete before moving to the next element.


      When to Use forEach() vs Other Methods:

      • Use forEach() for operations that require no return value.
      • Use map() if you need to create a new array based on the transformation.
      • Use filter() to create a new array with elements meeting a condition.
      • Use for...of or traditional loops for better control over iteration (like breaking or skipping elements).


      Methods in Array:

      • push()
      • unshift()
      • pop()
      • shift()
      • splice()
      • concat()


      Comments

      Post a Comment

      Popular posts from this blog

      Java Script - Table of Content

      Constraints in MySQL