JavaScript String length Property (original) (raw)

Last Updated : 29 Oct, 2024

The JavaScript length property is a fundamental feature **used to determine the number of characters in a string. It is essential for various string operations, such as validation, manipulation, and iteration. Understanding how to effectively use the length property can simplify tasks like checking input lengths, truncating strings, and dynamically adjusting content.

**Syntax

The syntax for using the length property is straightforward and applies directly to any string variable:

string.length

Examples of JS String Length Property

Here are examples demonstrating how the length property is used in JavaScript:

**Example 1: Measuring the Length of a Basic String

In this example, the string "GFG" contains three characters, so length returns 3.

JavaScript `

// JavaScript to illustrate length property
function func() {

// length property for string
console.log("GFG".length)

} func();

`

Example 2: Checking if a String is Empty

Here, we declare an empty string, emptyString, and use the length property to confirm if its length is 0. Since the string is empty, the comparison returns true.

JavaScript `

let emptyString = '';

console.log(emptyString.length === 0);

`

**Example 3: Accessing the Last Character of a String

For the string str = “GeeksforGeeks”, we can find the index of the last character by subtracting 1 from the string’s length. Since indexing starts at 0, the final index is 12.

JavaScript `

let str = 'GeeksforGeeks';

const lastIndex = str.length - 1; console.log(lastIndex);

`

The JavaScript length property is essential for working with strings efficiently. It helps with tasks like validating input, processing data, and adjusting content dynamically. This property makes string operations simpler and more accurate in your projects.

**Supported Browsers

The length property is well-supported across all major browsers, making it a reliable option in web development: