JavaScript Interview Question #161
What is tree shaking?
Performance, Browser APIs, Rendering & Modern Web Architecture Senior Advanced
Quick Interview Answer
Tree shaking is a build-time optimization that removes code determined to be unused from the final bundle. It works best with statically analyzable ES module imports and exports.
Detailed Explanation
Tree shaking is a build-time optimization that removes code determined to be unused from the final bundle. It works best with statically analyzable ES module imports and exports.
Whether code can actually be removed depends on the bundler, module structure, side effects, and configuration. Tree shaking is performed by build tooling rather than by the JavaScript language at runtime.
Code Example
// math.js
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;
// app.js
import { add } from "./math.js";
console.log(add(2, 3));
// A capable production bundler may omit unused multiply
// when it can safely prove that removal is valid.