Emmanuel Akinfulubi

JavaScriptString

Get the length of a string in JavaScript

Beginner · 4 min read

A username that needs at least three characters, a message box that stops at 280, a code that must be exactly ten characters long: all of these start with the same question. How long is this piece of text?

In this tutorial you will write a tiny function called size that tells you how many characters a string has. Along the way you will find out what counts as a character, and why you can read a string's length but never change it. You only need to know what a variable and a function are.

What a string is

A string is a piece of text inside quotes: 'Lagos', "hello", or '', the empty string with nothing inside. JavaScript gives each character a position number, called its index, starting from 0, not 1:

Positions

L  A  G  -  4  4  1  -  X  A
0  1  2  3  4  5  6  7  8  9

There are ten characters, so the positions run from 0 to 9. Keep that picture in mind: it explains one of the steps below.

Properties and methods

Every string carries some information around with it. A value you read off it is called a property. An action you call, with brackets after the name, is called a method. length is a property, so you write it with no brackets:

JavaScript

console.log('Lagos'.length);        // 5
console.log(typeof 'Lagos'.length); // 'number'

typeof tells you what kind of value something is. The length is a plain number, ready to compare or do sums with.

Here is the exercise. Try it on your own first if you like, or read on and we will build it together.

1 How long is a string?

easy

Report the length of a string. Then work out what length is actually counting, and whether you can change it.

Stuck? Three hints, smallest first
  1. 1. length is a property, not a method: no parentheses.
  2. 2. Spaces, tabs and punctuation are all characters, so they all count.
  3. 3. Strings are immutable. Try assigning to length and see what happens.

Step 1: read the length

Start with a car plate and a function that hands back its length.

Step 1

const plate = 'LAG-441-XA';
const size = (text) => text.length;
console.log(plate, 'has', size(plate), 'characters'); // LAG-441-XA has 10 characters

(text) => text.length is an arrow function: a short way to write a function that takes text and gives back text.length. The dashes count as characters, so the plate has 10, which matches the picture above.

Step 2: see what counts as a character

Everything inside the quotes counts, including the things you can't see.

Step 2

const size = (text) => text.length;
console.log(size(''));      // 0
console.log(size(' '));     // 1
console.log(size('a b c')); // 5
console.log(size('\t'));    // 1

The empty string has nothing in it, so its length is 0. A single space is one character, and the two spaces in 'a b c' count as well. '\t' is a tab. You type two symbols in your code, a backslash and a t, but the backslash is an escape: it tells JavaScript that the pair stands for one special character. So the string holds one tab, even though a tab looks wide on screen.

Step 3: use the length to reach the last character

Because positions start at 0, the last character sits at length - 1, not at length.

Step 3

const word = 'abc';
console.log(word.length);           // 3
console.log(word[word.length - 1]); // 'c'
console.log(word[word.length]);     // undefined

Square brackets after a string read the character at that index. word[3] is one step past the end, so there is nothing there and you get undefined, JavaScript's value for "nothing here". This off-by-one slip is very common, so it is worth seeing once on purpose.

Step 4: try to change the length

What if you want a shorter string? It is tempting to set the length, the way you would set any variable.

JavaScript

const s = 'abc';
s.length = 10;
console.log(s.length); // 3: nothing changed, and nothing told you

Strings in JavaScript are immutable: once a string is made, it can never be changed. Methods that look like they change a string actually give you a new one. So the assignment does nothing.

Doing nothing silently is a nasty kind of bug. That is why modern JavaScript code runs in strict mode, a stricter set of rules that turns silent failures like this into real errors. JavaScript modules and the answer panel on this page both use it. You switch it on in a plain script by writing 'use strict'; at the top:

Step 4

'use strict';
const refused = (() => {
  const s = 'abc';
  try {
    s.length = 10;
    return 'changed to ' + s.length;
  } catch (e) {
    return e.constructor.name;
  }
})();
console.log('assigning to length:', refused); // assigning to length: TypeError
console.log('abc'.length);                    // 3

There are three new pieces here. try { } catch (e) { } runs the code in try, and if it throws an error, jumps to catch with the error in e. e.constructor.name is the name of the error's type. The (() => { ... })() wrapper defines a function and calls it straight away, so refused ends up holding whatever it returns. The full error message reads Cannot assign to read only property 'length' of string 'abc'.

The full solution

Here is the complete answer, with the plate, the empty string and the refused assignment together. Press Run to see the output, then read the checks: each one is a fact from the steps above.

The answer

const plate = 'LAG-441-XA';

const size = (text) => text.length;

// Strings are immutable, so length is read-only. In strict mode, which is what
// a module and this panel both run in, assigning to it throws rather than being
// quietly ignored.
const refused = (() => {
  const s = 'abc';
  try { s.length = 10; return 'changed to ' + s.length; } catch (e) { return e.constructor.name; }
})();

console.log(plate, 'has', size(plate), 'characters');
console.log('the empty string has', size(''), 'characters');
console.log('assigning to length:', refused);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('the plate is ten characters', size(plate), 10);
test('the empty string is zero', size(''), 0);
test('a single space is one', size(' '), 1);
test('spaces inside a sentence count too', size('a b c'), 5);
test('length is a number, not a function', typeof 'abc'.length, 'number');
test('a tab is one character even though it looks wider', size('\t'), 1);
test('the last valid index is length - 1', 'abc'['abc'.length - 1], 'c');
test('assigning to length throws in strict mode', refused, 'TypeError');
test('so the value never changes', 'abc'.length, 3);

length is the count of UTF-16 code units, not of characters a reader would point at. For plain Latin text those are the same number, which is why the difference stays hidden until an emoji or an accent turns up — exercises 43 and 44 are where it stops being hidden.

The read-only part matters more than it looks. Assigning to length throws in strict mode and is silently ignored outside it, which is the worse of the two outcomes: code that looks like it truncated a string and did nothing at all.

Common mistakes

  • Writing text.length() with brackets. length is a number, not a method, so calling it gives TypeError: "Lagos".length is not a function.
  • Reading text[text.length] for the last character. Positions start at 0, so that is one past the end and gives undefined. Use text[text.length - 1].
  • Setting length to shorten a string. It never works on a string. Make a new, shorter string with slice instead.

Try it yourself

  1. Write isLongEnough(name) that returns true when a name has at least 3 characters. Test it with 'Al' and 'Ada'.
  2. Count the characters in 'Ada Lovelace' with and without the space. (Hint: replaceAll(' ', '') gives you a copy with the spaces taken out.)
  3. Check '👍'.length. You will see a surprise; the first link below explains it.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.