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

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

#1

Tell us what’s happening:
When finding the length of a string, do we begin count at 0 or 1?
Example:
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:


#2

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.


#3

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.


#4

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 https://en.wikipedia.org/wiki/Zero-based_numbering

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!


#5

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