Complex.js is a well tested JavaScript library to work with complex number arithmetic in JavaScript. It implements every elementary complex number manipulation function and the API is intentionally similar to Fraction.js. Furthermore, it's the basis of and .
let Complex = require('complex.js');let c = new Complex("99.3+8i");c.mul({re: 3, im: 9}).div(4.9).sub(3, 2);
A classical use case for complex numbers is solving quadratic equations ax² + bx + c = 0 for all a, b, c ∈ ℝ:
function quadraticRoot(a, b, c) { let sqrt = Complex(b * b - 4 * a * c).sqrt() let x1 = Complex(-b).add(sqrt).div(2 * a) let x2 = Complex(-b).sub(sqrt).div(2 * a) return {x1, x2}}// quadraticRoot(1, 4, 5) -> -2 ± i
For cubic roots have a look at RootFinder which uses Complex.js.
Parser
Any function (see below) as well as the constructor of the Complex class parses its input like this.
Returns the real part of the number if imaginary part is zero. Otherwise null
Trigonometric functions
The following trigonometric functions are defined on Complex.js:
Trig
Arcus
Hyperbolic
Area-Hyperbolic
sin()
asin()
sinh()
asinh()
cos()
acos()
cosh()
acosh()
tan()
atan()
tanh()
atanh()
cot()
acot()
coth()
acoth()
sec()
asec()
sech()
asech()
csc()
acsc()
csch()
acsch()
Notes on branches & ranges. Inverse trig on ℂ needs a branch choice. For acot there are two real-axis conventions:
(Chosen) Textbook range (0, π) on ℝ.
Gives familiar real values (acot(1)=π/4, acot(0)=π/2, acot(-1)=3π/4). With the principal complex branch this necessarily causes a π jump across the negative real axis (e.g., near -1±i0 → -π/4, but on -1 → 3π/4).
We implement this with atan2(1, x) to select the correct quadrant and handle x=0.
Alternative range (−π/2, π/2] on ℝ.
Makes acot(-1) = -π/4 and can avoid that specific jump only if the entire complex branch is changed to match. Using plain atan(1/x) silently adopts this convention, changes real outputs, is undefined at x=0, and still wouldn’t resolve the complex behavior without a broader policy change.
We therefore prefer predictable, textbook real values and robust quadrant handling—hence atan2(1, x)-accepting the implied branch cut on ℝ⁻ by design.
Geometric Equivalence
Complex numbers can also be seen as a vector in the 2D space. Here is a simple overview of basic operations and how to implement them with complex.js:
New vector
let v1 = new Complex(1, 0);let v2 = new Complex(1, 1);
As every library I publish, Complex.js is also built to be as small as possible after compressing it with Google Closure Compiler in advanced mode. Thus the coding style orientates a little on maxing-out the compression rate. Please make sure you keep this style if you plan to extend the library.
Building the library
After cloning the Git repository run:
npm installnpm run build
Run a test
Testing the source against the shipped test suite is as easy as
npm run test
Copyright and Licensing
Copyright (c) 2025, Robert Eisele
Licensed under the MIT license.