In this lesson, you read single characters out of a string to make a corner tag for the pizza party’s place cards: the guest’s first letter and last letter, Ge for Grace.
Key Points
- Every character in a string has a position, and JavaScript counts positions from
0. A position is the number of characters that come before it, so in"Grace",Gis at0andcis at3, even though it’s the fourth letter. - To read a character, write the name and then the position in square brackets:
guest[0]gives"G". - Every name has its own length, so don’t hard-code the last position. As long as the string isn’t empty, the last position is one less than its length:
guest[guest.length - 1]. JavaScript works outguest.length - 1first, and then reads that position. - A position the string doesn’t have gives
undefined, with no error.guest[5]isundefined, and an empty string""givesundefinedfor every position. A wrong position doesn’t stop your script, so check what it prints. at()also reads one position, and it takes a negative position that counts back from the end:guest.at(-1)gives the last character, the same asguest[guest.length - 1]. Onlyat()counts back. In square brackets,-1isn’t a position the string has, soguest[-1]givesundefined.- Reading a position copies a character out and leaves the string as it was. To get different text, you build a new string, like joining two characters with
+.
The Final Code
cards.js
const guest = "Grace";
const tag = guest[0] + guest.at(-1);
console.log(tag);