Understand [i][0]

In this code:

function titleCase(str) {
  str = str.split(" ");
  for (let i = 0; i < str.length; i++) {
    str[i] = str[i][0].toUpperCase() + str[i].substr(1);

  }
  return str.join(" ");
}

console.log(titleCase("I'm a little tea pot"));

I would like to understand what the “0” in str[i][0] represents and what it’s purpose is.

What’s the result of this code?

"I'm a little tea pot".split(" ")
1 Like

it creates an array of each of those words.

that is correct.
what will that array look like?

[“I’m”,”a”,”little”,”tea”,”pot”]

and how do i access each word of this array?

how do I access one letter of one word?

1 Like

The method used on the element [i][0] should also give some insight into what it is. What part of the string does using toUpperCase() make sense with? (within the requirements)

2 Likes

Others gave enough hints, but just in case it is still unclear, you can use brackets to reference an array item, or a string character(index), e.g. ['one', 'two', 8][2] and 'string value'[5] are both fair js syntax. You could even use it to reference object key(which could very much be seen as an index), as im sure you already know, e.g. { one: 'two' }['one']. We are used to see those “objects” masked under a variable name e.g. arr[5], name[2], obj[key], but under the hood they really estimate as their actual value(the given array, string etc). Having multiple brackets, just means referencing nested objects, whatever they could be(array/string/object), e.g. arr[0][i]['someKey'][4], what actually is referenced you must deduct by its origin in the code.

const arr = [
  [ 1, 2, 3, {
    someKey: 'striNg',
  }],
]

const i = 3

console.log(arr[0][i]['someKey'][4])
// logs "N"
2 Likes

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