UglifyJS works by parsing the JavaScript code and creating an Abstract Syntax Tree (AST). It then applies various transformations and optimizations to this AST, such as removing whitespace, shortening variable names, and eliminating dead code. The final step involves converting the optimized AST back into JavaScript code that is much smaller in size.