Use Bracket Notation to Find the Nth Character in a String_topic

Tell us what’s happening:
I didn’t understand the example. Couldn’t able to grep the concept in it. Please explain.

Your code so far

// Example
var firstName = "Ada";
var secondLetterOfFirstName = firstName[1];

// Setup
var lastName = "Lovelace";

// Only change code below this line.
var thirdLetterOfLastName = lastName[2];


Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36.

Link to the challenge:
https://www.freecodecamp.org/challenges/use-bracket-notation-to-find-the-nth-character-in-a-string

With indexed number series, we start with zero and count up e.g. 0, 1, 2, 3, …
Also we read from left to right, top to bottom.

Strings are an array of chars, and an Array begins with 0 and goes up to (n - 1) where n is equal to the length of the array. e.g. [0, 1, 2, 3…, n - 1]. Each char has an index number that matches it’s placement in the order of it’s position.

Let’s say you had a string, var myString = "FOO BAR" then you would have 7 different chars in order from left to right. Sense you start counting from zero you would represent the placement of each char as 0 = F, 1 = O, 2 = O, 3 = //whitespace, 4 = B, 5 = A, 6 = R.

One way to access a char value is to use [ square brackets ] at the end of a String the same way you would with accessing values from any Array. e.g.

var val = "FOO BAR"[5];
console.log("val is", val); // val is "A" 

Here’s a great place to learn more about String types.

1 Like

Thanks :slight_smile:

Thanks :slight_smile:

1 Like

I had the same question. Thank you for explaining!

1 Like