back to index

Shrinking JS: the Ternary

When the wire format is text, code size is cost — reach for the ternary.

published Aug 10, 2017 tags #javascript #minification

~/posts/minify-ternary $ cat post.md

/ LANG EN / 中文
/ THEME / /

JS is shipped (and largely executed) as text, so the first lever for making it smaller is just writing fewer characters. The ternary operator pulls disproportionate weight here.

Take this:

let a = 10;
if (a === 10) {
    return 123;
} else {
    return 456;
}

Six lines, plenty of characters. A slightly tighter version:

let a = 10;
if (a === 10) return 123;
else return 456;

The semicolon after return 123; is not optional.

Fewer lines, but return shows up twice; I also prefer not to drop JS semicolons unless I have solid test coverage.

The ternary form:

let a = 10;
return a === 10 ? 123 : 456;

One line. Same intent, less to read.

Hand-minification like this only goes so far. For real size savings on a build artifact, lean on a tool like uglify or terser — beyond the scope here.

back to index