JavaScript Arrays Ex. 3 - Hello World example


#1

Hi everyone, I have a question about the 'Fun Fact' for the JavaScript lesson on Arrays. In the first example, it says that when you count the number of characters in 'Hello World', the letter 'W' is the 6th character.

However, in the second example, the 'Fun Fact' says that the total number of characters in 'Hello World' is 11.

This leads me to wonder, do these examples count spaces in the string, or does the counting start at 0 or 1? If you follow the first example where 'W' is the 6th character, then the total number of characters in 'Hello World' is 10. If you follow the second example where the total number of characters totals 11, then it seems like it would count the space in 'Hello World'. Or....does it count the apostrophes?? I am so confused!


First example:
https://www.codecademy.com/courses/learn-javascript/lessons/arrays/exercises/property-access?action=lesson_resume&link_content_target=interstitial_lesson


Example 1:
Fun fact: You can also access each individual character in a string the same way you do with arrays. For instance, you can write:

var hello = 'Hello World';
console.log(hello[6]);
// Output: W



Example 2:
Fun fact: .length is also a property for strings.

For instance, you can write 'Hello World'.length, and it will output 11 (the number of characters in "Hello World").


#2

Ohhh I think I see how it works now.... because this page put 'Hello World' in red (whereas the lesson doesn't!). So in this case, the counting starts at 0 and includes the apostrophe (but not the space)? Someone please confirm! :slight_smile:


#3

The answer is:

The first example uses index to pick out a character. Index is the same as in arrays, and it always start counting from zero.

The second example just counts the length of the string, and it starts from one (it will be stupid if it threw a number that was subtracted with one) :grinning:

So it is two different things, because the index is only being used to pick out characters (in strings) or elements (in arrays)

Hope that helps!


#4

And it never count the quotes as a part of the string, they just mark that the text inside them is a string.
And it always count the spaces, too


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.