Cagri Metin
Cagri Metin

Reputation: 13

Parameter is seen as string Javascript

I just started using Javascript and I have a small beginner question.

I have created 2 functions, only when I place an argument for a function my 2 parameters are seen as a string and they are not added properly.

par1 = 5 , par2 = 2

function sum(par1,par2){
    
    return document.write("Sum : " + par1+par2 + "<br>");
}


function multi(par1,par2){
    
    return document.write(" Multi : "+par1*par2);
}

If I remove the "Sum:" + function from the sum function, it adds up well, but if I leave it in, my parameters are seen as string and I get result 52 instead of 7.

In multi function it just works well.

Thank you in advance for answering my question!

Upvotes: 1

Views: 607

Answers (3)

Isla McNeill
Isla McNeill

Reputation: 9

From my experience it does that because you are adding a string to an integer. If you do something like:

return ("Sum:", (par1 + par2))

That should work.

In JavaScript the '+' with a string just concatenates. For example:

const a = 1 + 1 // returns 2
const b = "2" + 2 // returns 22
const c = 3 + 3 + "3" + 3 // 633
const d = "Hello" + "World" + 4 // returns HelloWorld4

Upvotes: 0

Les Nightingill
Les Nightingill

Reputation: 6154

The reason is that when you write:

"some string"+5

javascript interprets the + operator as concatenate, because that's the only thing that's meaningful for a string, and it assumes that you are concatenating two strings.

Since ES6 javascript has string interpolation, you could write:

document.write(`Sum: ${par1 + par2} <br>`)

Upvotes: 1

StrayAnt
StrayAnt

Reputation: 379

Just wrap it with ().. example below

<!DOCTYPE html>

<head>
    
</head>
<body>
    


</body>
<script type="text/javascript">
    

function sum(par1,par2){
    //Wrap "par1" and "par2" with ()
    return document.write("Sum : " + (par1+par2) + "<br>");
}


function multi(par1,par2){
    //Wrap "par1" and "par2" with ()
    return document.write(" Multi : "+ (par1*par2));
}

sum(5,2);
multi(5,2);
</script>
</html>

Hope this helps

Upvotes: 0

Related Questions