How to add two numbers in JavaScript without using the “+” operator?

RMAG news

We can add two numbers in Javascript without using the + operator. Let me show you how to do this computation using JS functions.

Let’s start by declaring a function name add and pass in 2 parameters (a,b) to the function

const add = (a,b)=>{

}

After declaring the function, let’s now add the logic in the function block that will do the computation.

const add = (a,b)=>{
for(i = 1; i <= b; i++ ){
a++
}
return a
}

We initiates a for loop. The loop starts with i equal to 1 and continues as long as i is less than or equal to b. i is incremented by 1 in each iteration.

a++

Inside the loop, a is being incremented by 1 in each iteration. This effectively adds 1 to a, b times.

return a;

After the loop finishes, the value of a is returned. This will be the original value of a plus b.

console.log(add(3, 5)); //output: 8

Leave a Reply

Your email address will not be published. Required fields are marked *