Understanding string.length - 1: What It Means in JavaScript

preview_player
Показать описание
---

If anything seems off to you, please feel free to write me at vlogize [AT] gmail [DOT] com.
---

The Problem: Accessing Characters in a String

[[See Video to Reveal this Text or Code Snippet]]

In this function, we're trying to capture if the first character of beast matches the first character of dish, and similarly for the last character of both strings.

Zero-Based Indexing

Strings in JavaScript are zero-indexed: This means that the first character of a string is located at index position 0, the second character at index position 1, and so on.

Length vs. Index

Length of a String: The length property of a string returns the total number of characters in that string.

Since indexing begins at zero, the last character of a string can be accessed by subtracting 1 from the length. For example:

If a string’s length is 9, the character at the last index is 8, which is calculated as length - 1.

Visual Representation

Consider the example string "Hello Foo":

[[See Video to Reveal this Text or Code Snippet]]

From the above representation:

The length of the string "Hello Foo" is 9, but its last character o is found at index 8, thus:

[[See Video to Reveal this Text or Code Snippet]]

Conclusion: Why This Matters

Рекомендации по теме
visit shbcf.ru