PART II: ENTERING THE SECOND REALM
2.7 Looping over a string of characters
Do you still remember bracket notation and dot notation?
I introduced it on Part One, in the chapter Manipulating variable data.
Let’s review and expand a bit more about the topic.
I’m going to declare variable x with "orange" as the string value:
var x = "orange";
The value "orange" is a collection of sequential characters and each character has a location number starting at zero, like o is zero, r is one, a is two, n is three, etc.
We can use bracket notation to find the character data in any location of the string:
x[location Number]; <-- it gives us the value inside of the location.
It will display character "a" which is the third character and position 2 (counting from zero)
I can’t use dot notation here because dot notation does not accept numbers or symbols:
x.2 <-- this will give me an error.
What can we do with this bracket notation syntax?
Bracket notation allows us to address a specific character on the string value.
Here’s an example of displaying character g from variable x by sending x via a console.log:
Here’s another example: characters ge:
console.log(x + x);
So with bracket notation we can probe into a string of characters and fetch the contents of a location number.
What about dot notation?
Dot notation is good to grab properties of string values, such as length, remember?
· Dot syntax cannot be used with numbers, symbols, and names which values are not yet known when the code is being written. This prevents Dot syntax from being used in loops since the value in a loop will change for each loop cycle. So when it comes to dynamic data, only Bracket syntax can be used.