JavaScript array.length propertyThe length property returns the number of elements in an array in the form of a 32-bit unsigned integer. We can also say that the length property returns a number that represents the number of array elements. The return value is always larger than the highest array index. The length property can also be used to set the number of elements in an array. We have to use the assignment operator in conjunction with the length property to set an array's length. The array.length property in JavaScript is same as the array.size() method in jQuery. In JavaScript, it is invalid to use array.size() method so, we use array.length property to calculate the size of an array. SyntaxThe following syntax is used to return the length of an array The following syntax is used to set the length of an array For better understanding, let's see some of the illustrations of using array.length property. Example1It is a simple example to understand how to calculate the length of an array using the array.length property. Test it NowOutput In the output, we can see that length of the array is six, which is greater than the value of array's highest index. The highest index of the specified array in the above example is 5. Example2In this example, we are setting the length of an array by using the array.length property. Initially, the array contains two elements, so at the beginning, the length is 2. Then we increase the length of the array to 9. In the output, the values of the array are separated by commas. After increasing the length, the array contains two defined and seven undefined values separated by a comma. Then we insert five array elements and print them. Now, the array contains seven defined and two undefined values. Test it NowOutput In the next example, we will test the length property on the array with the non-numeric index. Example3In this example, the index of the array is non-numeric. Here, the array contains five elements with the non-numeric index. We are applying the length property on the given array to see the effect. Now let's see how the array.length property works on the non-numeric index of the array. Test it NowOutput In the output, we can see that the length of the array is displayed 0. After the execution of the above code output will be - We can also use the length property to find out the number of words in the string. Let's understand it with an example. Example4In this example, we are using the length property to display the number of words present in the string. Here, we are creating an array and use the split() function for the array elements. We are splitting the string from the whitespace (" ") character. If we direct apply the length property on the string, then it gives us the number of characters in the string. But in this example, we will understand how to calculate the number of words in the string. Test it NowOutput Next TopicJavaScript alert() |