Updated JavaScript implementation with toString() method.