Terser Show archive.org snapshot is a really good minifier ("compressor") for JavaScript code. I'm often surprised by the thoughtfulness of its compressed output.
Let's take this function:
function fn() {
  if (a) {
    return 'foo'
  } else if (b) {
    return 'foo'
  } else {
    return c()
  }
}
console.log(fn())
Terser will reduce this to the following code:
console.log(a||b?"foo":c())
Note how:
- The ifstatement has been replaced by a tertiary expression. This is often less readable, but it doesn't matter in compressed code.
- Multiple condition branches with the same effect have been into a single branch (a || b)
- The function fn()has been inlined, because it is only used once.
Let's use a similiar input, but call fn() twice:
function fn() {
  if (a) {
    return 'foo'
  } else if (b) {
    return 'foo'
  } else {
    return c()
  }
}
console.log(fn())
console.log(fn())
This compresses down to the following:
function o(){return a||b?"foo":c()}console.log(o()),console.log(o())
Note how:
- The function remains in the compressed output, as it is called more than once.
- The function name has been shortened to o, as it is not exported.
Let's look at a function without a condition:
const three = 3
function fn() {
  return 2 + three
}
console.log(fn())
console.log(fn())
This compresses down to the following:
console.log(5),console.log(5)
Note how:
- The function has been replaced by its constant output (5)
- Despite being called twice the function is now inlined, as that has fewer characters.
Posted by Henning Koch to makandra dev (2024-09-30 06:59)