You can create a String with the following code.
var firstName = "robert";
console.log("firstName is a " + typeof firstName);
You can see this code and run it at jsfiddle:
As I said, strings are a different, because each character in the string takes a byte to store, but the length of the string can not be determined until the variable has it's value set.
The Interpreter (and lower layers of technology, like web browser and the Operating System) still has the constraint that it must find contiguous memory to store the string in.
That means there is more work for the underlying layers to do to store your string.
var companyName = "Big House";
Take a look at Figure 7: string in memory.
VisualBasic used a type called a BString which used the first X bytes of the string to store its length. Of course, every time the string changes that value has to be updated.
The point to take away from this is that someone has to handle the issue that strings are of different lengths and the constraint that associated memory for a variable has to be contiguous.
What If The String Grows?
All of this should bring to mind the main problem. What if the string becomes longer, because you set it to a new string value?
For example, if later in the program you store:
companyName = "Big House Crafts";
Suddenly the program needs seven more contiguous bytes (one space plus six letters). But, what if the bytes past 0x00CD01 are already taken for use with other variables?
Strings Are Immutable
It's A Whole New String
That's because when you change a string like we did in the previous code, it doesn’t not just change the value stored at the original address. Instead, the original address is cleared and removed from the internal lookup table.
Then, the Interpreter
- calculates the amount of memory your new string is going to take,
- goes out and finds enough contiguous bytes,
- gets the new address,
- stores the address in the internal lookup table
- and finally, sets the value of those bytes.
You now have a whole new string -- a new address where the string is stored.
This also explains why adding characters to a string can be much slower (more processor intensive) than what is expected by the developer. There is much more work involved than just adding the new character to the end of the string.
That's all for this installment, but next time we'll dig a big deeper into strings and then talk about Reference types.
Keep on learning, keep on programming.