Find the Length of a String - Should we begin count at 0 or 1?

Tell us what’s happening:
When finding the length of a string, do we begin count at 0 or 1?
When finding the length of the string “Lovelace”, should the value of “L” be 0 or 1?

Your code so far

// Example
var firstNameLength = 0;
var firstName = "Ada";

firstNameLength = firstName.length;

// Setup
var lastNameLength = 0;
var lastName = "Lovelace";

// Only change code below this line.

lastNameLength = lastName.length;

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36.

Link to the challenge:

The length of a string is its number of characters. When you create a string, Javascript does the counting for you and stores the length in the .length attribute. If you have a string of one character, e.g. var mychar = "L", its length is 1, i.e. mychar.length === 1 is true.

1 Like

Oh I see. I was under the impression that we were to use zero-based indexing for this problem so we would begin count at 0 instead of 1.

You are correct, you are to use zero-based indexing. Index being the “address” of a particular character in the string (similar to numeric-based indexes in arrays). In computing, 0 (zero) is a valid number and the majority of programming languages use zero-based indexing

Length is how many characters are within the string. If we start counting at 0, the count would be off by one. If you count your fingers starting at 0, you end at 4. A 0 (zero) length string would mean an empty string: var str = “”;

Definitely confusing until you can wrap your head around the distinction. I find it easier to think of the indexes as “addresses” and not a numbering system!

This comes in the next challenges (which you might have done by now). To recap:

  • The length is the count of characters, so it’s the same number as when you count the characters yourself.
  • A particular character is referenced by its zero-based index in brackets:
    myString[0] for the first character
    myString[myString.length-1] for the last character