Bracket notation is the special syntax that allows us to access the individual characters that make up a string. To access a character, we use the syntax
i is the index of the character we want to access. String indices are integers representing the position of a character within a given string, and they start at 0. Thus, the first character of a string has index 0, the second has index 1, and so on.
Consider the string
"J" has index 0, the first
"a" has index 1,
"v" has index 2, and so on.
An expression of the form
someString[i] gives the character at index
This program prints out the initials of the person’s name.
What happens if we try to access an index that doesn’t exist, for example -1 or an index larger than the length of the string?
What does an expression using bracket notation evaluate to when the index is invalid (the index does not correspond to a character in the string)?
Check Your Understanding
phrase = 'Code for fun', then
phrase evaluates to:
Which of the following returns
myStr = 'Index'? Choose all correct answers.
myStr === 'n';
myStr === 'x';
myStr === ' ';
myStr === 'I';
What is printed by the following code?