Teachnique
      CourseRoadmaps
      Login

      OverviewPlacementSyntaxHello WorldConsole.log()CommentsVariableslet StatementConstantsData TypesType ConversionsStrict ModeReserved Keywords

      OperatorsArithmetic OperatorsComparison OperatorsLogical OperatorsBitwise OperatorsAssignment OperatorsConditional Operatorstypeof OperatorNullish Coalescing OperatorDelete OperatorComma OperatorGrouping OperatorYield OperatorSpread OperatorExponentiation OperatorOperator Precedence

      If...ElseWhile LoopsFor LoopFor...in LoopFor...of LoopLoop ControlBreak StatementContinue StatementSwitch CaseUser Defined Iterators

      FunctionsFunction ExpressionsFunction ParametersDefault ParametersFunction() ConstructorFunction HoistingArrow FunctionsFunction InvocationFunction call() MethodFunction apply() MethodFunction bind() MethodClosuresVariable ScopeGlobal VariablesSmart Function Parameters

      NumberBooleanStringsArraysDateMathRegExpSymbolSetsWeakSetMapsWeakMapIterablesReflectTypedArrayTempate LiteralsTagged Templates

      Objects OverviewClassesObject PropertiesObject MethodsStatic MethodsDisplay ObjectsObject AccessorsObject ConstructorsNative PrototypesES5 Object MethodsEncapsulationInheritanceAbstractionPolymorphismDestructuring AssignmentObject DestructuringArray DestructuringNested DestructuringOptional ChainingGlobal ObjectMixinsProxies

      HistoryVersionsES5ES6ECMAScript 2016ECMAScript 2017ECMAScript 2018ECMAScript 2019ECMAScript 2020ECMAScript 2021ECMAScript 2022

      CookiesCookie AttributesDeleting Cookies

      Browser Object ModelWindow ObjectDocument ObjectScreen ObjectHistory ObjectNavigator ObjectLocation ObjectConsole Object

      Web APIHistory APIStorage APIForms APIWorker APIFetch APIGeolocation API

      EventsDOM Events

      Feedback

      Submit request if you have any questions.

      Course
      Arrays

      JavaScript Tutorial

      This JavaScript tutorial is crafted for beginners to introduce them to the basics and advanced concepts of JavaScript. By the end of this guide, you'll reach a proficiency level that sets the stage for further growth. Aimed at empowering you to progress towards becoming a world-class software developer, this tutorial paves the way for a successful career in web development and beyond.

      Arrays Object

      The JavaScript Array object lets you store multiple values in a single variable. An array is used to store a sequential collection of multiple elements of same or different data types. In JavaScript, arrays are dynamic, so you don't need to specify the length of the array while defining the array. The size of a JavaScript array may decrease or increase after its creation.

      Syntax

      Use the following syntax to create an Array object in JavaScript
      const arr = new Array(val1, val2, val3, ..., valN)

      Parameters

      • val1, val2, val3, ..., valN − It takes multiple values as an argument to initialize an array with them.

      Return value

      It returns an array object.
      When you pass the single numeric argument to the Array() constructor, it defines the array of argument length containing the undefined values. The maximum length allowed for an array is 4,294,967,295.
      You can add multiple comma separated elements inside square brackets to create an array using the array literal
      const fruits = [ "apple", "orange", "mango" ];
      You will use ordinal numbers to access and to set values inside an array as follows.
      fruits[0] is the first element
      fruits[1] is the second element
      fruits[2] is the third element

      Array Properties

      Here is a list of the properties of the Array object along with their description
      Sr.No.
      Property & Description
      1
      AI
      Returns a reference to the array function that created the object.
      2
      AI
      Reflects the number of elements in an array.
      3
      AI
      The prototype property allows you to add properties and methods to an object.

      Array Methods

      Here is a list of the methods of the Array object along with their description

      Array Static methods

      These methods are invoked using the Array class itself:
      Sr.No.
      Method & Description
      1
      AI
      Creates a shallow copy of the array.
      2
      AI
      Returns boolean values based on the argument is an array.
      3
      AI
      Creates an array from multiple arguments.

      Array Instance Methods

      These methods are invoked using the instance of the Array class:
      Sr.No.
      Method & Description
      1
      AI
      To get element from the particular index.
      2
      AI
      Returns a new array comprised of this array joined with another array (s) and/or value(s).
      3
      AI
      To Copy part of the array into the same array at different locations.
      4
      AI
      To get each entry of the array.
      5
      AI
      Returns true if every element in this array satisfies the provided testing function.
      6
      AI
      To fill the array with static values.
      7
      AI
      Creates a new array with all of the elements of this array for which the provided filtering function returns true.
      8
      AI
      To find an element satisfying the condition.
      9
      AI
      To find an index of the element satisfying the condition.
      10
      AI
      To find an element satisfying the condition from the last.
      11
      AI
      To find an index of the element satisfying the condition from the last.
      12
      AI
      To flatten the array.
      13
      AI
      To get a new array after flattening the array.
      14
      AI
      Calls a function for each element in the array.
      15
      AI
      Returns a boolean value if the array contains the specific element.
      16
      AI
      Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
      17
      AI
      Joins all elements of an array into a string.
      18
      AI
      Returns an array iterator containing the key for each array element.
      19
      AI
      Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
      20
      AI
      Creates a new array with the results of calling a provided function on every element in this array.
      21
      AI
      Removes the last element from an array and returns that element.
      22
      AI
      Adds one or more elements to the end of an array and returns the new length of the array.
      23
      AI
      Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.
      24
      AI
      Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.
      25
      AI
      Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.
      26
      AI
      Removes the first element from an array and returns that element.
      27
      AI
      Extracts a section of an array and returns a new array.
      28
      AI
      Returns true if at least one element in this array satisfies the provided testing function.
      29
      AI
      Represents the source code of an object.
      30
      AI
      Sorts the elements of an array.
      31
      AI
      Adds and/or removes elements from an array.
      32
      AI
      To convert array elements into the string.
      33
      AI
      Returns a reverse of the array.
      34
      AI
      This method returns a new array with some elements removed and/or replaced at a given index.
      35
      AI
      Returns a string representing the array and its elements.
      36
      AI
      Adds one or more elements to the front of an array and returns the new length of the array.
      37
      AI
      To get an iterator containing values of each array index.
      38
      AI
      This method returns a new array with the element at the given index replaced with the given value.

      Example: Creating JavaScript Array Object

      In the example below, the array 'strs' is initialized with the string values passed as an Array() constructor's argument.
      The 'cars' array contains 20 undefined elements. If you pass multiple numeric values, it defines the array containing those elements but needs to be careful with a single numeric argument to the array() constructor.
      <html>
      <head>
      <title> JavaScript - Array() constructor </title>
      </head>
      <body>
      <p id = "demo"> </p>
      <script>
      const output = document.getElementById("demo");
      
      let strs = new Array("Hello", "World!", "Tutorials Point");
      output.innerHTML += "strs ==> " + strs + "<br>";
      
      let cars = new Array(20);
      output.innerHTML += "cars ==> " + cars + "<br>";
      </script>
      </body>
      </html>

      Output

      strs ==> Hello,World!,Tutorials Point
      cars ==> ,,,,,,,,,,,,,,,,,,,

      Example: Creating Arrays Using Array Literal

      In the example below, we have created different arrays. The arr1 array contains the numbers, the arr2 array contains the strings, and the arr3 array contains the boolean values.
      <html>
      <head>
      <title> JavaScript - Array literals </title>
      </head>
      <body>
      <p id = "output"> </p>
      <script>
      const arr1 = [10, 40, 50, 60, 80, 90]; // Array of numbers
      const arr2 = ["Hello", "Hi", "How", "are", "you?"]; // Array of strings
      const arr3 = [true, false, true, true]; // Array of booleans
      
      document.getElementById("output").innerHTML =
      "arr1 ==> " + arr1 + "<br>" +
      "arr2 ==> " + arr2 + "<br>" +
      "arr3 ==> " + arr3;
      </script>
      </body>
      </html>

      Output

      arr1 ==> 10,40,50,60,80,90
      arr2 ==> Hello,Hi,How,are,you?
      arr3 ==> true,false,true,true

      Accessing JavaScript Array Elements

      The array index starts from 0. So, you can access the array element using its index.
      let number = arr[index]
      In the above syntax, 'arr' is an array, and 'index' is a number from where we need to access the array element.

      Example

      In the example below, we have created the array of numbers and accessed the elements from the 0th and 2nd index of the array. The element at the 0th index is 1, and the element at the 2nd index is 6.
      <html>
      <head>
      <title> JavaScript - Accessing array elements </title>
      </head>
      <body>
      <p id = "output"> </p>
      <script>
      const nums = [1, 5, 6, 8, 90];
      document.getElementById("output").innerHTML =
      "Element at 0th index is : " + nums[0] + "<br>" +
      "Element at 2nd index is : " + nums[2];
      </script>
      </body>
      </html>

      Output

      Element at 0th index is : 1
      Element at 2nd index is : 6

      JavaScript Array length

      The 'length' property of the array is used to find the length of the array.
      let len = arr.length;

      Example

      In the example below, the 'length' property returns 5, as array contains 5 elements.
      <html>
      <head>
      <title> JavaScript - Array length </title>
      </head>
      <body>
      <p id = "output"> </p>
      <script>
      const nums = [1, 5, 6, 8, 90];
      document.getElementById("output").innerHTML =
      "Array length is : " + nums.length;
      </script>
      </body>
      </html>

      Output

      Array length is : 5

      Adding a new element to the array

      You can use the push() method to insert the element at the end of the array. Another solution is that you can insert the array at the index equal to the array length.
      arr.push(ele)
      OR
      arr[arr.length] = ele;
      In the above syntax, 'ele' is a new element to insert into the array. Here, if the array length is N, the array contains elements from 0 to N – 1 index. So, we can insert the new element at the Nth index.

      Example

      In the example below, we insert 6 to the array using the push() method. Also, we used the 'length' property to insert the element at the end.
      <html>
      <body>
      <p id = "output"> </p>
      <script>
      const output = document.getElementById("output");
      const nums = [1, 2, 3, 4, 5];
      nums.push(6); // Inserting 6 at the end
      output.innerHTML += "Updated array is : " + nums + "<br>";
      nums[nums.length] = 7; // Inserting 7
      output.innerHTML += "Updated array is : " + nums + "<br>"
      </script>
      </body>
      </html>

      Output

      Updated array is : 1,2,3,4,5,6
      Updated array is : 1,2,3,4,5,6,7

      Updating Array Elements

      To update any array element, you can access the array index and change its value.
      arr[index] = ele;
      In the above syntax, 'index' is an index where we need to update a value with the 'ele' value.

      Example

      In the example below, we update the element at the first index in the array.
      <html>
      <body>
      <p id = "output"> </p>
      <script>
      const nums = [1, 2, 3, 4, 5];
      nums[0] = 100; // Updating first element
      document.getElementById("output").innerHTML =
      "Updated array is : " + nums;
      </script>
      </body>
      </html>

      Output

      Updated array is : 100,2,3,4,5

      Traversing the Arrays

      You can use the loop to traverse through each array element. However, some built-in methods exist to traverse the array, which we will see in later chapters.
      for (let p = 0; p < nums.length; p++) {
      // Access array using the nums[p]
      }

      Example

      In the below code, the array contains 5 numbers. We used the for loop to traverse the array and print each element.
      However, while and do-while loops can also be used to traverse the array.
      <html>
      <body>
      <p id = "demo"> </p>
      <script>
      const output = document.getElementById("demo");
      const nums = [1, 2, 3, 4, 5];
      for (let p = 0; p < nums.length; p++) {
      output.innerHTML += "nums[" + p + "] ==> " + nums[p] + "<br>";
      }
      </script>
      </body>
      </html>

      Output

      nums[0] ==> 1
      nums[1] ==> 2
      nums[2] ==> 3
      nums[3] ==> 4
      nums[4] ==> 5