Archive for August 4, 2007

JavaScript Concatenation Operation: The Plus Sign

Posted in JavaScript, programming on August 4, 2007 by Joey

The JavaScript concatenation operator is the plus sign. As shown in the example below, the plus sign in JavaScript can be used to concatenate strings:

var strA = 'Joey';
var strB = 'JavaScript';
var strC = strA + ' ' + strB;
document.write(strC);//Result is Joey JavaScript

Strings can also be concatenated with the shorthand assignment operator +=, as follows:

var strA = 'Joey';
var strB = ' JavaScript';
var strC = strA += strB;
document.write(strC);//Result is Joey JavaScript

A number concatenated with a string, results in a string, as follows:

var strA = 'Joey';
var strB = 5;
var strC = strA += strB;
document.write(strC); //Result is Joey5

If two numbers are concatenated together, JavaScript is no longer concatenating, as this is now an addition operation:

var strA = 5;
var strB = 5;
var strC = strA += strB;
document.write(strC);//Result is 10

Had one or both of the numbers been in quotes, however, JavaScript will treat this as a string operation:

var strA = '5';
var strB = 5;
var strC = strA += strB;
document.write(strC);//Result is 55

How to Get the Length of a String in JavaScript

Posted in JavaScript, programming on August 4, 2007 by Joey

To retrieve the length of a JavaScript string, access the length property of the JavaScript string object, as follows:

var strTest = 'Joey JavaScript';
document.write(strTest.length);

Note that an empty string has a length of 0.

JavaScript True, False: Checking for Boolean Values

Posted in JavaScript, programming on August 4, 2007 by Joey

Checking if a value is true or false is simple in JavaScript. All values evaluate to true, except for:

0
-0
null
undefined
NaN
empty string
false

For example, the following results in false being output since the empty string evaluates to false.

var testVar = ''
if (testVar)
document.write('true');
else
document.write('false');

It should also be noted that the literal strings '0' and 'false' evaluate to true.