Understanding Arrays in JavaScript

An array in data structure that stores a collection of elements, typically of the same type, in contiguous memory locations. Each element in an array is accessed by its numerical index. Arrays are commonly used in programming to organize and manipulate data efficiently. They offer advantage such as random access, constant-time access to individual elements, and support for iteration and manipulation operations.

  • What is an Array in JavaScript?
  • An array in JavaScript is a special variable that can hold more than one value at a time. It's linear data structure consisting of a collection of elements, each identified by at least one index or key.
    Arrays in JavaScript can hold elements of any data type, including numbers, strings, objects, and even other arrays. They provide methods for manipulation and iteration, making them versatile for various programming tasks.

  • Why JavaScript arrays are different from other programming language?
  • Here are some reasons why JavaScript arrays are different from other programming languages :
    Dynamic Typing : JavaScript arrays can hold elements of different data types within the same array. This flexibility is not present in all programming languages.
    Dynamic Sizing : JavaScript arrays are dynamically sized, meaning they can grow or shrink in size as needed. Other languages might require specifying the size of the array upfront.
    Sparse Arrays : JavaScript arrays can have holes or gaps in them, meaning they can have elements with non-sequential indices. Other languages typically maintain contiguous memory allocation for arrays.
    Built-in Methods : JavaScript arrays come with a variety of built-in methods for manipulation and iteration, making them very powerful and versatile compared to arrays in some other languages.
    Overall, JavaScript arrays are designed to be flexible and easy to use, catering to the dynamic nature of web development.

  • Creating Arrays in JavaScript:
  • Method 1 : Using Array literal
  • let myArray=[1,2,3,4,5];
  • Method 2 : Using the Array constructor
  • let array1=new Array(1,2,3,4,5);

  • Add Elements in an Array:
  • There are several ways to add elements to an array in JavaScript :
    push() method : Adds one or more elements to the end of an array and returns the new length of the array.

    let array=[1,2,3];
    array.push(4);
    // array is now [1,2,3,4]

    unshift() method : Adds one or more elements to the beginning of an array and returns the new length of the array.

    let array=[2,3];
    array.unshift(1);
    // array is now [1,2,3]

    splice() method : Adds or remove elements from an array at a specified index.

    let array=[1,2,3];
    array.splice(1,0,4);
    // array is now [1,4,2,3]
  • JavaScript Array methods :
  • JavaScript arrays come with a variety of built-in methods for manipulation and iteration. Some of the most commonly used methods include :

    Methods Description
    concat(): Joins two or more arrays and returns a new array.
    copyWithin(): Copies array elements within the array, to and from specified positions.
    entries(): Returns a new Array Iterator object that contains the key/value pairs for each index in the array.
    every(): Checks if every element in an array pass a test provided by a function.
    fill(): Fills all the elements of an array from a start index to an end index with a static value.
    filter(): Creates a new array with all elements that pass the test provided by a function.
    find(): Returns the value of the first element in an array that satisfies the provided testing function.
    findIndex(): Returns the index of the first element in an array that satisfies the provided testing function.
    flat(): Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
    flatMap(): Maps each element using a mapping function, then flattens the result into a new array.
    forEach(): Calls a function for each element in the array.
    includes(): Determines whether an array includes a certain value among its entries, returning true or false as appropriate.
    indexOf(): Returns the first index at which a given element can be found in the array, or -1 if it is not present.
    isArray(): Determines whether the passed value is an Array.
    join(): Joins all elements of an array into a string.
    keys(): Returns a new Array Iterator object that contains the keys for each index in the array.
    lastIndexOf(): Returns the last index at which a given element can be found in the array, or -1 if it is not present.
    pop(): Removes the last element from an array and returns that element.
    push(): Adds one or more elements to the end of an array and returns the new length of the array.
    reverse(): Reverses the order of the elements in an array in place.
    toString(): Returns a string representing the specified array and its elements.
  • Examples :
  • JavaScript code
    Write a program to find the sum and average of the numbers of a given Single Dimensional array.
    <!DOCTYPE html> <html> <head> <title></title> </head> <script type="text/javascript"> var a=[]; var n=prompt("Enter the array range"); for(var i=0;i<n;i++) { a[i]=parseInt(prompt("Enter the no")); } var s=0; for(var i=0;i<n;i++) { s=s+a[i]; } var avg=s/n; document.write("Sum="+s+"Average="+avg); </script> </html>

    Output :
    Enter the array range : 3
    Enter the no : 1
    Enter the no : 2
    Enter the no : 3
    Sum=6Average=2

    JavaScript code
    Write a program to find the greatest number of the given Single Dimensional Array.
    <!DOCTYPE html> <html> <script type="text/javascript"> var a=[]; var n=prompt("Enter range"); for(var i=0;i<n;i++) { a[i]=parseInt(prompt("Enter the no.")); } var max=a[0]; for(var i=0;i<n;i++) { if(max<a[i]) max=a[i]; } document.write("Largest= "+max); </script> </html>

    Output :
    Enter range : 3
    Enter the no. 2
    Enter the no. 3
    Enter the no. 5
    Largest= 5

    JavaScript code
    Write a program to store temperatures °F in S.D.A and display all the temperatures after converting them into °C.
    <!DOCTYPE html> <html> <script type="text/javascript"> var f=[]; var c=[]; var p; var n=prompt("Enter range"); for(var i=0;i<n;i++) { f[i]=parseFloat(prompt("Enter no.")); } for(var i=0;i<n;i++) { p=f[i]; c[i]=parseFloat((p-32)*0.56); } for(var i=0;i<n;i++) { document.write("Celcius="+c[i]+"<br>"); } </script> </html>

    Output :
    Enter range : 3
    Enter no. 50
    Enter no. 100
    Enter no. 80
    Celcius=10.080000000000002
    Celcius=38.080000000000005
    Celcius=26.880000000000003

    JavaScript code
    Write a program to enter a set of Integers. Sort the numbers in ascending order by using Bubble sort technique.
    <!DOCTYPE html> <html> <head> <title></title> </head> <script type="text/javascript"> var a=[1,5,3,2,4]; for(i=0;i<5;i++) { for(j=0;j<4;j++) { if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } document.write('Sorted Array:'+'<br>') for(i=0;i<5;i++) { document.write(a[i] +' '); } </script> </html>

    Output :
    Sorted Array: 1 2 3 4 5

  • Conclusion :
  • Arrays are versatile and powerful data structures in JavaScript, essential for storing and manipulating collections of data. Mastering arrays is crucial for writing efficient and effective JavaScript code. Practice using arrays and their methods to become more comfortable with them.