how to perform addition in Node Js?

Viewed 40

This is my code

const calculator = (req, res) => {
    let option = req.body.option
    let num1 = req.body.num1
    let num2 = req.body.num2
    //console.log(num1 + num2)

    if (option == '+') {
        res.status(200).send({
            success: true,
            result: num1 + num2
        })
    }
}

module.exports = { calculator }

I am trying to add num1 and num2, for eg num1 = 2 and num2 = 2 expected result should be 'result: 4'

but instead of result: 4 I am getting result: 22

3 Answers

This is because both variable are 'string' when you get from request.

Use this as result

result: Number(num1) + Number(num2)

Ref: Number()

const req = {
  body: {
    num1: '1',
    num2: '2'
  }
};

const num1 = parseInt(req.body.num1);
const num2 = parseInt(req.body.num2);

console.log('sum:', num1 + num2);

That's because num1 and num2 are strings. You propably get the values from and input field which always translates anything entered to a string.

Just do

 let num1 = parseInt(req.body.num1)
 let num2 = parseInt(req.body.num2)

and you're good to go.

Or shorter

            result: +num1 + +num2

as +'2' for js engine is equivalent to Number('2')

Related