0
0
JavascriptHow-ToBeginner · 3 min read

How to Find Length of String in JavaScript Easily

In JavaScript, you can find the length of a string by using the .length property. This property returns the number of characters in the string, including spaces and special characters.
📐

Syntax

The syntax to get the length of a string is simple. Use the string variable followed by .length.

  • string.length: Returns the number of characters in the string.
javascript
let myString = "Hello";
let length = myString.length;
💻

Example

This example shows how to find the length of different strings, including spaces and special characters.

javascript
const greeting = "Hello, world!";
const empty = "";
const spaces = "  ";

console.log(greeting.length);  // 13
console.log(empty.length);     // 0
console.log(spaces.length);    // 2
Output
13 0 2
⚠️

Common Pitfalls

Some common mistakes when finding string length include:

  • Trying to call length() as a function instead of using the property length.
  • Expecting length to count words instead of characters.
  • Not considering that spaces and special characters count as characters.
javascript
const text = "Hello";

// Wrong: length is not a function
// console.log(text.length()); // Error

// Right:
console.log(text.length); // 5
Output
5
📊

Quick Reference

PropertyDescriptionExample
.lengthReturns number of characters in string"Hello".length // 5
AccessUse with string variable or literallet s = "abc"; s.length // 3
Includes spacesCounts spaces and special chars"a b".length // 3
Not a functionDo not use parentheses"abc".length() // Error

Key Takeaways

Use the .length property to get the number of characters in a string.
.length counts all characters including spaces and special symbols.
Do not use parentheses; .length is a property, not a function.
Empty strings have length 0.
Remember .length counts characters, not words.