Open In App

JavaScript Program to Find the Length of a String

Last Updated : 19 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a String, the task is to find the length of a given string in JavaScript. This task is fundamental in string processing and is commonly encountered in various programming scenarios. The program provides a simple yet effective solution to calculate the length of any string input, enabling developers to assess the string data size accurately.

These are the following approaches:

Using the length Property

This approach directly utilizes the built-in length property of strings in JavaScript, which returns the number of characters in the given string.

Example: This example shows the length of the given string by the use of the .length() method.

Javascript
function findStrLength(str) {
    return str.length;
}

// Driver Code
let str = "Hello World";
let len = findStrLength(str);

console.log(len);

Output
11

Iterative Approach

In this method, iterates over each characters of the string using a loop and increments a counter variable to keep track of the total number of characters.

Example: This example shows the length of the given string by the use of the loop.

Javascript
function findStrLength(str) {
    let length = 0;
    for (let i = 0; i < str.length; i++) {
        length++;
    }
    return length;
}

// Driver Code
let str = "Hello World";
let len = findStrLength(str);

console.log(len);

Output
11

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads