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
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.
Top comments (4)
Not the fastest way...
Try this:
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.
Waoh, I never knew that was actually possible.
It is very possible. Check this out as well