Java Reference
In-Depth Information
JavaScript would assume that you want to treat the number as a string and concatenate the two
together, the number being converted to text automatically. The variable theResult would contain
"2323" —the concatenation of 23 and 23 , and not the sum of 23 and 23 , which would be 46 .
The same applies to objects. If you declare a primitive string and then treat it as an object, such as
by trying to access one of its methods or properties, JavaScript will know that the operation you're
trying to do won't work. The operation will only work with an object; for example, it would be
valid with a String object. In this case, JavaScript converts the plaintext string into a temporary
String object, just for that operation, and destroys the object when it's finished the operation.
So, for your primitive string mySecondString , you can use the length property of the String
object to find out the number of characters it contains. For example:
var lengthOfSecondString = mySecondString.length;
This would store the data 22 in the variable lengthOfSecondString .
The same ideas expressed here are also true for number and boolean primitives and their
corresponding Number and Boolean objects. However, these objects are not used very often, so we
will not be discussing them further in this topic.
javasCript's native objeCt tYpes
So far, you have just been looking at what objects are, how to create them, and how to use them.
Now take a look at some of the more useful objects that are native to JavaScript—that is, those that
are built into the JavaScript language.
You won't be looking at all of the native JavaScript objects, just some of the more commonly used
ones, namely the String object, the Math object, the Array object, and the Date object.
string objects
Like most objects, String objects need to be created before they can be used. To create a String
object, you can write this:
var string1 = new String("Hello");
var string2 = new String(123);
var string3 = new String(123.456);
However, as you have seen, you can also declare a string primitive and use it as if it were a String
object, letting JavaScript do the conversion to an object for you behind the scenes. For example:
var string1 = "Hello";
Using this technique is preferable. The advantages to doing it this way are that there is no need to
create a String object itself, and you avoid the troubles with comparing string objects. When you
try to compare string objects with primitive string values, the actual values are compared, but with
String objects, the object references are compared.
 
Search WWH ::




Custom Search