JavaScript length property


The length property in JavaScript is a built-in property that returns the number of elements in an array or the number of characters in a string. It is a non-negative integer that indicates the size of the array or string.

Length Property for Strings

For strings, the length property returns the number of UTF-16 code units in the string, which generally corresponds to the number of characters.

Syntax:

string.length

Example 1: Basic Usage

let message = "Hello, World!"; console.log(message.length); // 13

In this example, the length property returns 13 because there are 13 characters in the string "Hello, World!", including spaces and punctuation.

Example 2: Special Characters

The length property counts all UTF-16 code units, which may not correspond directly to the number of visible characters for certain Unicode characters.

let emojiStr = "😊"; // A single emoji console.log(emojiStr.length); // 2

Here, the length is 2 because the emoji "😊" is represented by two UTF-16 code units.

Length Property for Arrays

For arrays, the length property returns the number of elements in the array.

Syntax:

array.length

Example 3: Basic Usage

let fruits = ["apple", "banana", "cherry"]; console.log(fruits.length); // 3

In this example, the length property returns 3 because there are three elements in the fruits array.

Example 4: Empty Arrays

If the array is empty, the length property will return 0.

let emptyArray = []; console.log(emptyArray.length); // 0

In this case, the length is 0 because there are no elements in the array.

Example 5: Modifying the Length Property

You can also modify the length property of an array to change the number of elements it contains. This can truncate or expand the array.

let numbers = [1, 2, 3, 4, 5]; numbers.length = 3; console.log(numbers); // [1, 2, 3]

In this example, setting numbers.length = 3 truncates the array to only include the first three elements.

Summary:

  • The length property provides the number of characters in a string or the number of elements in an array.
  • For strings, it counts UTF-16 code units, which can result in a length that does not equal the number of visually displayed characters for certain emojis or special characters.
  • For arrays, it indicates how many items are currently stored in the array.
  • The length property can also be modified for arrays to change their size.