DEV Community

The Coder
The Coder

Posted on โ€ข Edited on

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

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)=>{

}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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++
Enter fullscreen mode Exit fullscreen mode

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

return a;

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

Click here to watch the video on Youtube

Top comments (10)

Collapse
ย 
seanhurwitz profile image
seanhurwitz โ€ข
function add(x,y) {
return Array(x).fill("").concat(Array(y).fill("")).length
}
Enter fullscreen mode Exit fullscreen mode
Collapse
ย 
ticha profile image
The Coder โ€ข

Great solution! However, it might not work well for large and negative numbers

Collapse
ย 
kiliaosi profile image
wangzhi โ€ข
function add(x, y) {
    while (y != 0) {
        let carry = x & y;
        x = x ^ y;
        y = carry << 1;
    }
    return x;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
ย 
ticha profile image
The Coder โ€ข

Great solution! I think you should consider how it will handle floating point numbers!

Collapse
ย 
citronbrick profile image
CitronBrick โ€ข

Here's mine:

    function add(a,b) {
        return a - (b * -1);
    }
Enter fullscreen mode Exit fullscreen mode

Thanking my 8th grade teachers for this :)

Collapse
ย 
slobodan4nista profile image
Slobi โ€ข โ€ข Edited
function add(a,b) {
        return -(-a-b);
    }
Enter fullscreen mode Exit fullscreen mode
Collapse
ย 
ticha profile image
The Coder โ€ข

Hey there! Your function for addition is clever and brings back some nostalgic memories with your shoutout to your 8th-grade teachers. I appreciate the humor and personal touch in the comment!

Collapse
ย 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ โ€ข
let a = 5
a += 2
Enter fullscreen mode Exit fullscreen mode

No + operator here! :)

Collapse
ย 
ticha profile image
The Coder โ€ข

:)

Collapse
ย 
citronbrick profile image
CitronBrick โ€ข

You can enable syntax highlighting in dev using

triple backtick javascript
code
triple backtick