DEV Community

Kiruthiga S
Kiruthiga S

Posted on

Array in js

Array

  • An Array is an object type designed for storing data collections
  • An array is an ordered list of values. Each value, known as an element, is assigned a numeric position in the array called its index
  • The indexing starts at 0, so the first element is at position 0, the second at position 1, and so on
  • Arrays can hold any type of data-such as numbers, strings, objects, or even other arrays-making them a flexible and essential part of JavaScript programming

Syntax

let arrayName = [value1, value2, value3];
Enter fullscreen mode Exit fullscreen mode

Example

let numbers = [2, 4 , 8, 12, 16];
console.log(numbers);
Enter fullscreen mode Exit fullscreen mode

Output:(5) [2, 4, 8, 12, 16]

Create Array using Literal
Creating an array using array literal involves using square brackets [] to define and initialize the array

let a = [];
console.log(a);

let b = [10, 20, 30];
console.log(b);
Enter fullscreen mode Exit fullscreen mode

Output: [10, 20, 30]

Create using new Keyword (Constructor)
The "Array Constructor" refers to a method of creating arrays by invoking the Array constructor function

let c = new Array(10, 20, 30);
console.log(c);
Enter fullscreen mode Exit fullscreen mode

Output:(3) [10, 20, 30]

const d = new Array();
const e = new Array(3);
const f = new Array("3");
const g = new Array("Saab", "Volvo", "BMW");
console.log(d);
console.log(e);
console.log(f);
console.log(g);
Enter fullscreen mode Exit fullscreen mode

Output: [empty × 3]
'3' ['Saab', 'Volvo', 'BMW']


    const marks = [70, 90, 99, 30, 75];

    let total = 0;
    let result = "Pass";
    let highest = marks[0];

    for (let i = 0; i < 5; i++) {
        if (marks[i] < 35) {
            result = "Fail";
        }
        total = total + marks[i];
        if (marks[i] > highest) {
            highest = marks[i];
        }
        console.log(marks[i]);
    }
    console.log(result);
    console.log(total);
    console.log(highest);
    // total=marks[0]+marks[1]+marks[2]+marks[3]+marks[4];
    // console.log(total);
Enter fullscreen mode Exit fullscreen mode

Output:70
90
99
30
75
Fail
364
99

Top comments (0)