feat(curriculum): Add interactive examples to What Is Bracket Notation, and How Do You Access Characters from a String (#63189)

This commit is contained in:
Clarence Bakosi
2025-10-28 23:07:35 +01:00
committed by GitHub
parent 64a3e5af19
commit 06c1a1fb49
@@ -5,7 +5,7 @@ challengeType: 19
dashedName: what-is-bracket-notation-and-how-do-you-access-characters-from-a-string
---
# --description--
# --interactive--
In JavaScript, strings are treated as sequences of characters, and each character in a string can be accessed using bracket notation. This allows you to retrieve a specific character from a string based on its position, which is called its index.
@@ -15,31 +15,43 @@ For example, in the string `hello`, the character `h` is at index `0`, `e` is at
Bracket notation uses square brackets (`[]`) and the index of the character you want to access. Lets look at an example:
:::interactive_editor
```js
let greeting = "hello";
console.log(greeting[1]); // Output: "e"
console.log(greeting[1]); // "e"
```
:::
In this example, we can access the character at index `1`, which is `e`.
To get the last character of a string, you can use the length of the string minus one.
The `length` property of a string tells you how many characters it contains, so to access the last character, you would subtract one from the length:
:::interactive_editor
```js
let greeting = "hello";
console.log(greeting[greeting.length - 1]); // Output: "o"
console.log(greeting[greeting.length - 1]); // "o"
```
:::
In this case, the `length` of `hello` is `5`, and the last character (`o`) is at index `4` which is `5 - 1`.
If you want to get multiple characters, you can use bracket notation like this:
:::interactive_editor
```js
let greeting = "hello";
let firstTwo = greeting[0] + greeting[1]; // Output: "he"
let firstTwo = greeting[0] + greeting[1]; // "he"
console.log(firstTwo);
```
:::
In this example, we are concatenating the first and second characters using bracket notation to form the string `he`.
Bracket notation is useful when you need to access specific characters in a string, such as extracting initials from a name or checking a specific letter for validation.