DEV Community

Cover image for How to multiply two numbers in JavaScript with out using the * operator?
The Coder
The Coder

Posted on Edited on

How to multiply two numbers in JavaScript with out using the * operator?

Here's a clever way to multiply numbers in JavaScript without using the "*" operator. The method is quite efficient and involves just a few steps.

We begin by defining a function called multiply using ES6 arrow function syntax, which takes two parameters a and b.

const multiply = (a, b) => {
    return ("i").repeat(a).repeat(b).length;
}


console.log(multiply(3, 5)); // Output should be 15
console.log(multiply(7, 2)); // Output should be 14

Enter fullscreen mode Exit fullscreen mode

Let's break it down:

We create a string consisting of a single character, "i", using ("i").
Then, we repeat this string a times using .repeat(a), effectively creating a string of length a.
Next, we repeat this resulting string b times using .repeat(b), effectively creating a string of length a * b.
Finally, we retrieve the length of this concatenated string, which gives us the result of multiplying a by b.
This method cleverly leverages the .repeat() method to achieve multiplication without using the "*" operator.

Watch full video on Youtube

Top comments (4)

Collapse
 
efpage profile image
Eckehard •

Not the fastest way...

Try this:

const multiply = (a,b) => {
  let c = b
  const run = (a,b) =>  a>1 ? run(a-1,b+c) : b
  return run(a,b)
}

console.log(multiply(3, 5)); // Output should be 15
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ticha profile image
The Coder •

It is worth noting that there are multiple methods that can be used. However, this method that you just showed me is a great one as well.

Collapse
 
prophethacker profile image
Mokom Collins Awah •

Waoh, I never knew that was actually possible.

Collapse
 
ticha profile image
The Coder •

It is very possible. Check this out as well