Last updated
Last updated
This will be our final programming concept that we use a while loop. We will be accessing individual characters of a string.
Assign a variable to represent the length of the string
Create a variable initialized to zero to help us "index" the characters in the string
While the index variable is less than the length of the string
Repeatedly access the string at the given index
Make sure to increase the index towards length of the string to eventually terminate the loop
hello, world!
Prompt for Input: The program asks the user to enter a word and stores this word in a variable called word
.
Initialize Index Variable: The program sets up a variable to keep track of the current position (or index) in the word, starting at 0 in a variable called i
.
Get Length of the Word: The program calculates the total number of characters in the word by accessing the length property and stores this number in another variable called size
.
While Loop: The program enters a loop that will continue to run as long as the current index is less than the total number of characters in the word.
Print Character and Index: Inside the loop, the program prints the current character from the word along with its position (index).
Increment Index: After printing the character and its index, the program increases the index by 1 to move to the next character.
In JavaScript, you can index a value at a string by using either the method called .at()
or using the []
notation.