Some Javascript Idioms

It’s common to find yourself assigning a value to a variable that might or might not be null. A first-pass approach to coalescing a value into that variable might look like this:

Ensuring a value is set
1
2
3
4
5
6
7
//userInput may or may not be valid
var Foo;
if (userInput) {
    Foo = userInput;
} else {
    Foo = defaultValue;
}

A more concise way would be to use the ternary operator:

Ternary to set a value
1
var Foo = (userInput) ? userInput : defaultValue;

This is much better. It’s still readable, but is also more expressive. The third way (that I prefer) is to use a Boolean operator in assignment, like so:

OR for a default value
1
var Foo = userInput || defaultValue;

This works exactly like the ternary: if userInput is ‘falsey’, the evaluation of the Boolean continues, and Foo is assigned the value of defaultValue. If userInput is “truthy”, however, evaluation of the OR statement stops, because one side of the Boolean has evaluated to true.

A similar trick can be done using the AND operator:

Protecting a reference call on an object with AND
1
2
3
var Bar = false;
var Baz = 'string';
var Foo = Bar && Baz; //results in false

but

AND Behavior
1
2
3
var Bar = 'prerequisite';
var Baz = 'string';
var Foo = Bar && Baz; //results in Foo == 'string';

These two way of conditionally assigning value to a variable can be used to make javascript quite expressive while maintaining readability. Go forth and code.