JavaScript is definitely an interesting language. Unlike typical server-side code, we will often sacrifice readability for brevity in order to save a few bytes. Thanks to the many JavaScript compression apps out there, we don’t have to worry about this as much. But there are a few shortcuts I like to use from time to time which keep my client script terse, albeit a little less readable than using alternative means.
|| as a null coalescing operator
A null coalescing operator returns the value to its right only if the value to its left is null. Here is an example of a null coalescing operator (??) in C#:
public string GetWebAddress(protocol, url)
{
protocol = protocol ?? "http://";
return protocol + url;
}
string p = "https://";
string url = "www.mysite.com";
string address = getWebAddress(p, url); // returns "https://www.mysite.com"
string address = getWebAddress(null, url); // returns "http://www.mysite.com"
There is no null coalescing operator in JavaScript. However, you can use the logical OR operator (||) in its place. Here is similar code in JavaScript:
function getWebAddress(protocol, url) {
protocol = protocol || "http://";
return protocol + url;
}
var p = "https://", url = "www.mysite.com";
var address1 = getWebAddress(p, url); // returns "http://www.mysite.com"
var address2 = getWebAddress(null, url); // returns "https://www.mysite.com"
This is logically equivalent to
function getWebAddress(protocol, url) {
if (protocol === null) {
protocol = "http://";
}
return protocol + url;
}
var p = "https://", url = "www.mysite.com";
var address1 = getWebAddress(p, url); // returns "http://www.mysite.com"
var address2 = getWebAddress(null, url); // returns "https://www.mysite.com"
But the first method, using the logical OR operator, is much more compact.
!! for quick boolean conversion
You can quickly cast JavaScript variables to boolean values using the double exclamation (!!). This operation will convert any non-null, non-zero value to true and all others to false.
var obj = { name: 'Kevin' };
var arr = [ '1', 0, '0' ];
var a = !!true; // True
var b = !!false; // False
var c = !!'true'; // True
var d = !!'false'; // True
var e = !!5; // True
var f = !!0; // False
var g = !!null; // False
var h = !![]; // True
var i = !!{}; // True
var j = !!'undefined'; // True
var k = !!obj.name; // True
var l = !!obj.age; // False
var m = !!arr[0]; // True
var n = !!arr[1]; // False
var o = !!arr[2]; // True
var p = !!arr[3]; // False
Enjoy!
