I like variables with units. Since dimensionally typed computation isn’t reasonably possible in JavaScript due—probably for the better—to a lack of operator overloading, I think it’s nice to include units in variable names, e.g. delay_seconds
or delay_s
. That can get a little unwieldy. density_kg_per_m3
? G_m3_per_kg_s2
? Perhaps when presentation is a priority, a more modest goal is to label units where values are defined. When using Observable, I often append units in comments, e.g. delay = 10 // seconds
, but comments get hidden with the cell input:
fmt`delay = ${10} seconds`
Use on observablehq.com by importing from @rreusser/fmt:
import { fmt } from '@rreusser/fmt'
In its simplest form, it passes a single value through a tagged template and styles it like an Observable output.
fmt`c = ${299792458} m/s`
In order to access the value, you’ll need to use Observable Desktop’s `view` keyword. Since Observable doesn’t permit reflection on the cell content which would allow determining the name of the assigned variable, this means we need to duplicate the name.
const c = view(fmt`c = ${299792458} m/s`);
c
The value is shown in the inspector theme color (purple in Observable Desktop, green on the web) and content to the right of it is colored gray.
fmt`ρ = ${2700} kg/m³`
fmt`ρ = ${2700} ${tex`\mathrm{kg / m^3}`}`
import { Inspector } from 'npm:@observablehq/inspector'
fmt`object = ${{ foo: 'bar' }}`
fmt`boolean = ${true} ${{ foo: 'bar' }}`
fmt`area = ${tex`\displaystyle \int_0^\pi \sin x\,dx`} = ${2}`
import { Tangle } from 'observable:@mbostock/tangle'
const n = view(fmt`n = ${Tangle({ min: 0, max: 100, value: 48 })} cookies`)
n
fmt(x => x.toExponential(2))`E = ${70e9} Pa`
fmt('.2e')`E = ${70e9} Pa`
fmt(sci())`E = ${70e9} Pa`
fmt(sci('.3f'))`E = ${70e9} Pa`
const myFormatter = fmt(sci('.3f'));
myFormatter`E = ${70e9} Pa`
myFormatter('~f')`E = ${70e9} Pa`