What is Javascript Length?
Introduction
In this article, we look at what the Javascript length function does, where it could be used, and its limitations.Table of Contents
- What is Javascript Length?
- Using of Javascript Length on Strings
- Using Javascript Length on Arrays
- Other Related Concepts
What is Javascript Length?
Before we take a look at the code and its uses let’s first understand what the Length function in javascript does.The length function in Javascript is used to return the length of an object. And since length is a property of an object it can be used on both arrays and strings. Although the syntax of the length function remains the same, bear in mind that the interpretation of length varies between arrays and strings. I’ve explained each case in detail below.
Syntax of Javascript Length function
X.length
//returns the length of X
Here X can be either a string or an array.
Using Javascript Length on strings:
While using Javascript length on a string, the function returns the number of characters present in the string. And in case the string is empty it returns 0.const xyz = "Hello World!";
console.log(xyz.length);
// Output: 12
Using Javascript Length on Arrays:
While using Javascript length on an array, the function returns the number of elements in the array. And similarly it returns 0 in the array is empty.const xyz = ['bat', 'ball', 'mat', 'pad'];
console.log(xyz.length);
// Output: 4
Note: While dealing with the length function remember that the length of an object is always greater than the index of it’s last element.