Does code always return the last character?

Asked

Viewed 52 times

3

I have the following code

var browserType = 'mozillad';
var browserType2 = browserType[browserType.length-1];

document.write(browserType2);

Because he returns d it is returning the last character but explain me why put browserType inside the parentheses and then use the length property to -1 and then it’s gonna work

  • Leandro, if one of the answers solved your problem, you can choose the one that best solved it and accept it, see here how and why to do it. It is not mandatory, but it is a good practice of the site, to indicate to future visitors that it solved the problem. You can only accept one of them, but don’t forget that you can also vote in all the answers you found useful.

3 answers

5

The variable browserType contains a String 'mozillad'. In Javascript you can measure the length of a string (the number of characters) by accessing the property .length of the same. In this case making console.log('mozillad'.length); gives 8.

In Javascript, to access one of these characters can be used 'texto'[posiçãoDoCaracter], that is to say 'mozillad'[0] will return the first letter m. What can be confusing here is that the index for the first letter is 0, and not 1. This is a feature of the language. And following the same reasoning to get the last letter you can use 'mozillad'[7]. And again, notice that here we use 7 and not 8 because we started at zero.

So your code in practice is:

'mozillad'[8 - 1]

which is exactly console.log('mozillad'[7]);, that is to say: d

  • 1

    well explained example thanks

4

.length, when used in a string (in this case, 'mozzilad'), returns the number of characters of this string. 'mozzilad' has 8 characters, carrying browserType.length - 1 is equal to 8 - 1 = 7.

By accessing browserType as an array, using the index browserType.length-1, browserType[browserType.length-1] will return the 8th character, which is at index 7 of the array.

              0  1  2  3  4  5  6  7 // Índices da array
              1º 2º 3º 4º 5º 6º 7º 8º // browserType possui 8 caracteres
browserType: [m, o, z, z, i, l, a, d]
                                   ^ // Caractere a ser retornado

Remember that the array indexes start counting from 0 (index 0, index 1, etc.), and the number of characters starts from 1 (1st character, 2nd character, etc.), so -1 is placed in the .length.

  • Thank you helped a lot of hugging

  • +1 - good idea to add the indexes next to the letters

  • Thank you, I usually understand more easily when there is a "visual" representation of the explanation, so I try to put them in my answers when I see that

0

It is returning d pq you are accessing the last character Browsertype[whole Arry index] q in the above case is Browsertype.length -1 which is total of -1 positions

Browser other questions tagged

You are not signed in. Login or sign up in order to post.