Home

Search

JavaScript Length Examples

Use the length property to get lengths of strings and arrays. Test length performance.

Length. A string has a certain number of characters. With length we can access this value. An array too has a certain length—which may be zero.

To get the length, we access the length property. This is performed in constant time—it is much faster than looping and counting. But there is some overhead to length versus a local var.

String length. This program uses the length property to get the number of characters in the string. An example string "cat" has 3 characters.
JavaScript program that uses string, length var animal = "cat"; // Write the string and its length. document.write(animal + "; " + animal.length); Output cat; 3

Array length. Here we declare an array literal with four numbers in it. We then access its length—which returns 4. We call push() to add a number to our array, so length now returns 5.Array
Tip: Length is constant but only for an object at a point in time. If a local variable changes, the length too changes.
JavaScript program that uses array, length // Get length of array. var sizes = [10, 11, 12, 13]; document.write(sizes.length + "; "); // Push element and get length again. sizes.push(14); document.write(sizes.length + "; "); Output 4; 5;

Performance, string length. The length value is stored in the JavaScript engine, so it is a simple value access in memory. But this has some overhead versus a local variable.
Program 1: This program calls the length property on a string many times. The length is accessed in the hot part of the loop.
Program 2: The program uses a cached local variable to avoid calling length more than once. It accesses the local in the loop.
Result: In Google Chrome in 2016 the length cache is slightly faster. In a real page, this difference would likely not be noticeable.
JavaScript program that benchmarks length var x1 = performance.now(); var text = "carrot"; var result = 0; // Test string length. for (var i = 0; i < 100000000; i++) { if (text.length === 6) { result++; } } var x2 = performance.now(); document.title = (x2 - x1) + "/" + result; JavaScript program that benchmarks length cache variable var x1 = performance.now(); var text = "carrot"; var textLength = text.length; var result = 0; // Test string length with local cache. for (var i = 0; i < 100000000; i++) { if (textLength === 6) { result++; } } var x2 = performance.now(); document.title = (x2 - x1) + "/" + result; Output 208 ms access length 201 ms access length cached var

A review. Arrays and strings have lengths in JavaScript. Accessing a length is fast, but using a local variable to cache the length is still faster.

Home
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.