totn JavaScript

JavaScript: String length property

This JavaScript tutorial explains how to use the string property called length with syntax and examples.

Description

In JavaScript, length is a string property that is used to determine the length of a string. Because length is a property of the String object, it must be invoked through a particular instance of the String class.

Syntax

In JavaScript, the syntax for the length property is:

string.length;

Parameters or Arguments

There are no parameters or arguments for the length property.

Returns

The length property returns an integer value that represents the number of characters in the string.

If the string is an empty string, the length property will return 0.

Note

  • The length property is a string property and not a string method. However, we have included the length property within our JS String Methods section because you will most likely use this property in conjunction with the String methods found in this section.
  • The length property is read-only.

Example

Let's take a look at an example of how to use the length property in JavaScript.

For example:

var totn_string = 'TechOnTheNet';

console.log(totn_string.length);

In this example, we have declared a variable called totn_string that is assigned the string value of 'TechOnTheNet'. We have then invoked the length property of the totn_string variable to return the number of characters in the string.

We have written the output of the length property to the web browser console log, for demonstration purposes, to show what the length property returns.

The following will be output to the web browser console log:

12

In this example, the length property returned a value of 12 which is the number of characters in the string 'TechOnTheNet'.