There are three main styles of white-space separation that are used. I’ll use a haversine formula for the example, so that a combination of functions, numbers, and variables can be seen.
if(!Math.TAU){Math.TAU=Math.PI*2;}
function degreesToRadians(deg){return deg*Math.TAU/360;}
function haversine(lat1,lon1,lat2,lon2){
var earthRadius=6372.8,//km
dLat=degreesToRadians(lat2)-degreesToRadians(lat1),
dLon=degreesToRadians(lon2)-degreesToRadians(lon1),
a=Math.pow(Math.sin(dLat/2),2)+Math.pow(Math.sin(dLon/2),2)*Math.cos(lat1)*Math.cos(lat2),
c=2*Math.asin(Math.sqrt(a));
return earthRadius*c;
}
The above is a style that many consider to be too cramped to easily make out names and details when they are used within the code.
if (!Math.TAU) {
Math.TAU = Math.PI * 2;
}
function degreesToRadians(deg) {
return deg * Math.TAU / 360;
}
function haversine(lat1, lon1, lat2, lon2) {
var earthRadius = 6372.8, // km
dLat = degreesToRadians(lat2) - degreesToRadians(lat1),
dLon = degreesToRadians(lon2) - degreesToRadians(lon1),
a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2),
c = 2 * Math.asin(Math.sqrt(a));
return earthRadius * c;
}
The above tends to be the default spacing style, primarily due to it being used in the ECMASCRIPT specifications. Also, the spaces between operands act as punctuation, helping you to more easily understand what’s going on.
if ( !Math.TAU ) {
Math.TAU = Math.PI * 2;
}
function degreesToRadians ( deg ) {
return deg * Math.TAU / 360;
}
function haversine ( lat1, lon1, lat2, lon2 ) {
var earthRadius = 6372.8, // km
dLat = degreesToRadians( lat2 ) - degreesToRadians( lat1 ),
dLon = degreesToRadians( lon2 ) - degreesToRadians( lon1 ),
a = Math.pow( Math.sin( dLat / 2 ), 2 ) + Math.pow( Math.sin( dLon / 2 ), 2 ) * Math.cos( lat1 ) * Math.cos( lat2 ),
c = 2 * Math.asin( Math.sqrt( a ) );
return earthRadius * c;
}
The above tends to result in lines of code that are around 10% longer in length, and seems to make it trickier to interpret the operations being performed. When all of the code is equally spread out it’s more difficult to determine what’s important.