 js question | Sololearn: Learn to code for FREE!

+6

# js question

Why put two numbers together as a string instead of adding two numbers? Function func(num1,num2) { return (num1+num2);}

+3

You can see this: https://code.sololearn.com/Wa11A18a138A

+2

Is your question about "how to put two numbers together" or as you written "why put..." clarify it pls.. What your goal by code sample..?

+2

other operators have no meaning for string (in js), so operands are implicitly casted to number if needed ;P

+1

Jayakrishna🇮🇳 I want two numbers to be “+” sum ! This code puts two numbers together

+1

num1 and num2 are parameter which are passed in function as a parameter so if you want to add two number then just call the function and pass values in function like this: sum = func(10, 5); sum = 15 Your parameters value can be anything like 20 and 10, 30 and 40, 50 and 60 depending upon user input.

+1

+ operator is used for concatenating string as well as adding numbers... when at least one of its operand is of type text, js assume you want concatenate them (and do an implicit cast if necessary) if you get number input from user, you get it as their string representation ^^ to safely use number input, cast it explicitly (or half-explicitly) to number: var str1 = "38", str2 = "4"; var num1 = Number(str1); var num2 = +str(str2); var res1 = str1+str2; // "384" var res2 = num1+num2; // 42 there are also the functions parseInt() and parseFloat: var str = "98.7cm"; var n1 = Number(str); // NaN var n2 = +str; // NaN var n3 = parseFloat(str); // 98.7 var n4 = parseInt(str); // 98

+1

🅰🅹 🅐🅝🅐🅝🅣 That's right, thank you! But one question is why for other operators it considers the input of the text box as a number but for the sum of the strings?

+1

SiMiN zr When you take value from input then it would be considered as a string value so you need to cast that string value with Number function. If you see my code I have done that because '+' can be used to add two numbers and also can be used to concat two string.

+1

SiMiN zr Other operators considers as a number because we can not do string operation on other operators like ( /, *, % - ) so JavaScript automatically converts that textbox value as a number.

+1

🅰🅹 🅐🅝🅐🅝🅣 visph Ok, thank you ☺️☺️🌹🌹

+1

SiMiN zr seems it solved already.. just adding. May be you are passing values as strings.. otherwise it's works for addition only. function func(num1,num2) { return (num1+num2); } console.log(func(2,3)); //output:5 console.log(func("2","3")); //output:23

0

return num1.toString() + num2.toString()

0

0

SiMiN zr Use to "toString()" method for this.

-1

🅰🅹 🅐🅝🅐🅝🅣 I want the user to enter the parameters in a textbox and display the sum of the two numbers, The sum of the numbers after the call is not displayed