You can take advantage of the fact that all variables are truthy or falsy in JavaScript. In other words, every variable can be coerced (converted) into true or false.
null is falsy, and strings with content are truthy. That means:
var a = null;
var b = 'hello';
if (a) {
// does not run
} else {
// runs
}
if (b) {
// runs
}
You can use other kinds of expressions too, like a ternary expression or the logical OR operator:
alert(a ? 'yes' : 'no'); // => no
alert(b ? 'yes' : 'no'); // => yes
alert(a || b); // => hello
In this case, logical OR is our most interesting choice. When you use the operator, the following happens:
- If the left side evaluates truthy, return that value.
- Otherwise, return the value that the right side evalutes to.
In the above example, a is null, so it is falsy. The expression returns the right side, the value of b. So we can take advantage of this behavior by writing varFirstName || '', which will either return the first name (if there is one), or if it's null, the right side gives us an empty string.
function ShowFullName() {
var varFirstName = Xrm.Page.getAttribute("lauren_firstname").getValue();
var varLastName = Xrm.Page.getAttribute("lauren_lastname").getValue();
Xrm.Page.getAttribute("lauren_name").setValue(((varFirstName || '') + " " + (varLastName || '')).trim());
}
I added a call to trim to remove extra spaces from the result.