While JavaScript might not be the ideal language to write a production compiler, you might enjoy the “Create Your Own Compiler” tutorial that does an annotated walkthrough of “The Super Tiny Compiler” ...
The compiler analyzed it, optimized it, and emitted precisely the machine instructions you expected. Same input, same output.