3D Game Programming

(C. Jardin) #1

Strings


Strings in JavaScript are kind of boring. You can really only join two strings
into larger strings. What is interesting is that the plus operator is what joins
them together. Try the following in the JavaScript console.

varstr1 ="Howdy";
varstr2 ="Bob";

str1 +" "+ str2;
// "Howdy Bob"

Pretty crazy, isn’t it? Given that there are no multiplication and division keys
on most keyboards, there definitely are no stick-two-strings-together keys.
So JavaScript gets lazy and uses the plus sign again.

What do you suppose happens if you try to join a string and a number? Well,
give it a try:

varstr ="The answer to 7 + 4 is ";
varanswer = 7 + 4;

str + answer;

Try This Yourself

Do this and check it in the JavaScript console!


The result is that, when combining a string and a number, JavaScript will
treat the number as a string:

varstr ="The answer to 7 + 4 is ";
varanswer = 7 + 4;

str + answer;
// "The answer to 7 + 4 is 11"

Booleans


There is not much to a Boolean. It is either true or false. It is possible to convert
Booleans with the not operator. In JavaScript, the exclamation point is the not
operator:

varyes = true;
varthe_opposite = !yes;
varthe_opposite_of_the_opposite = !!yes;
yes;
// true
the_opposite;

report erratum • discuss

Changing Things • 73


Prepared exclusively for Michael Powell

Free download pdf