console.log(4 + 5 + "6");
console.log("4" + 5 + 6);
I think it is something related to element type(string, number)
But I can not find the proper document explaining this concept.
Whenever a number and a string are added together, the number turns into a string. Because of this adding 4 and 5 will equal 9, because they are both numbers, but adding 4.toString() and 5.toString() will result in 45, because the + operator isn't actually adding, it is joining two strings.
When you do console.log(4 + 5 + "6");, the numbers 4 and 5 are being mathematically added first, which is 9, and then 9 gets converted into a string and 6 gets added on to it.
When you do console.log("4" + 5 + 6);, the number 5 gets converted into a string and joined to the string "4". Same thing happens with the 6. This results in the string 456.
Like #Pointy said, this can be changed by changing the order of operations. Parenthesis will be calculated first. For example, console.log("4" + (5 + 6)); will result in 411, because the 5 and 6 will be mathematically added first, then converted into a string and added on to 4.
Great question, and I didn't think about that until today :)
Most operators in JavaScript expressions are evaluated left to right, so 4 + 5 + "6" is interpreted as (4 + 5) + "6". Thus the numeric addition is performed first, followed by the string concatenation. In the second example, the left-most operand is a string, so both + operations are string concatenation.
parseFloat("10.1") + parseFloat("32.3")
vs
+ "10.1" + + "32.3"
both statement will produce the same result 42.4
using this statement:
+ "10.1" + + "32.3"
Why does + act like a parse and how each statement affects the performance in the program?
JavaScript uses implicit conversions. The unary + only accepts numbers, so, when you give it a string, it converts it into a number. JavaScript does this by parsing the string as a number. Since JavaScript doesn't have an integer type, it is always parsed as a floating point number.
To answer the performance question: jsperf.
From my tests, the unary operator + is 8 times faster than parseFloat.
I'd guess this has to do with the expense of function calls in JS, etc.
This question already has answers here:
Javascript (+) sign concatenates instead of giving sum of variables
(14 answers)
Closed 6 years ago.
JavaScript:
console.log('adding' + addThis + '+' + p1 +'=' + (addThis + p1));
Console in browser returns: adding3+0=30
Im debugging a loop that interpolates two numbers. It works fine until addThis (the amount that needs to be added to the original number) is exactly 3 and p1 (the original value) is 0.
Every time the difference(addThis) has no decimals a wrong calculation happens.
So same problem at:
adding6+0=60 ...or at..
adding9+0=90
...all cases in between work fine (e.g. console returns: adding3.5999999999999996+0=3.59999999999999960)
Dose it 'forget' the point?
Dose it treat those values as strings?
I can't share the whole code but the problem has to be in this simple calculation right?
Thanks a lot for your thoughts and knowledge! ;)
3+0=30. It seems like it must be the string (at least anyone variable is string). You can re-visit the lines where those variable values are initialized/changed. Else you can use like the below:
addThis=Number(addThis); p1=Number(p1);
console.log('adding' + addThis + '+' + p1 +'=' + (addThis + p1));
If you want to convert the strings to integers you can use the parseInt function:
addThis = '3'
p1 = '0'
console.log('adding' + addThis + '+' + p1 +'=' + (parseInt(addThis) + parseInt(p1)))
So javascript uses the plus operator to concatenate strings with strings and/or integers like so:
<script>document.write("One plus Two equals " + 3);</script>
<script>document.write("One plus Two equals " + "three");</script>
At least I think it does :/ --Because of this, things get confusing if I wanted to concatenate integers and/or strings with arithmetic. I shall try here anyway. don't laugh :(
<script>document.write("One plus Two equals " + 1+2);</script>?
I wonder, could the solution as easy as adding moar parentheses?!
<script>document.write("One plus Two equals " + (1+2));</script>
Am I way off base here?
Why when I use this: (assuming i = 1)
divID = "question-" + i+1;
I get question-11 and not question-2?
Use this instead:
var divID = "question-" + (i+1)
It's a fairly common problem and doesn't just happen in JavaScript. The idea is that + can represent both concatenation and addition.
Since the + operator will be handled left-to-right the decisions in your code look like this:
"question-" + i: since "question-" is a string, we'll do concatenation, resulting in "question-1"
"question-1" + 1: since "queston-1" is a string, we'll do concatenation, resulting in "question-11".
With "question-" + (i+1) it's different:
since the (i+1) is in parenthesis, its value must be calculated before the first + can be applied:
i is numeric, 1 is numeric, so we'll do addition, resulting in 2
"question-" + 2: since "question-" is a string, we'll do concatenation, resulting in "question-2".
You may also use this
divID = "question-" + (i*1+1);
to be sure that i is converted to integer.
Use only:
divID = "question-" + parseInt(i) + 1;
When "n" comes from html input field or is declared as string, you need to use explicit conversion.
var n = "1"; //type is string
var frstCol = 5;
lstCol = frstCol + parseInt(n);
If "n" is integer, don't need conversion.
n = 1; //type is int
var frstCol = 5, lstCol = frstCol + n;
Since you are concatenating numbers on to a string, the whole thing is treated as a string. When you want to add numbers together, you either need to do it separately and assign it to a var and use that var, like this:
i = i + 1;
divID = "question-" + i;
Or you need to specify the number addition like this:
divID = "question-" + Number(i+1);
EDIT
I should have added this long ago, but based on the comments, this works as well:
divID = "question-" + (i+1);
divID = "question-" + parseInt(i+1,10);
check it here, it's a JSFiddle
Another alternative could be using:
divID = "question-" + (i - -1);
Subtracting a negative is the same as adding, and a minus cannot be used for concatenation
Edit: Forgot that brackets are still necessary since code is read from left to right.
Add brackets
divID = "question-" + (i+1);
using braces surrounding the numbers will treat as addition instead of concat.
divID = "question-" + (i+1)
The reason you get that is the order of precendence of the operators, and the fact that + is used to both concatenate strings as well as perform numeric addition.
In your case, the concatenation of "question-" and i is happening first giving the string "question=1". Then another string concatenation with "1" giving "question-11".
You just simply need to give the interpreter a hint as to what order of prec endence you want.
divID = "question-" + (i+1);
Joachim Sauer's answer will work in scenarios like this. But there are some instances where adding parentheses won’t help.
For example: You are passing “sum of value of an input element and an integer” as an argument to a function.
arg1 = $("#elemId").val(); // value is treated as string
arg2 = 1;
someFuntion(arg1 + arg2); // and so the values are merged here
someFuntion((arg1 + arg2)); // and here
You can make it work by using Number()
arg1 = Number($("#elemId").val());
arg2 = 1;
someFuntion(arg1 + arg2);
or
arg1 = $("#elemId").val();
arg2 = 1;
someFuntion(Number(arg1) + arg2);
var divID = "question-" + (parseInt(i)+1);
Use this + operator behave as concat that's why it showing 11.
Care must be taken that i is an integer type of variable. In javaScript we don't specify the datatype during declaration of variables, but our initialisation can guarantee that our variable is of a specific datatype.
It is a good practice to initialize variables of declaration:
In case of integers, var num = 0;
In case of strings, var str = "";
Even if your i variable is integer, + operator can perform concatenation instead of addition.
In your problem's case, you have supposed that i = 1, in order to get 2 in addition with 1 try using (i-1+2). Use of ()-parenthesis will not be necessary.
- (minus operator) cannot be misunderstood and you will not get unexpected result/s.
One place the parentheses suggestion fails is if say both numbers are HTML input variables.
Say a and b are variables and one receives their values as follows (I am no HTML expert but my son ran into this and there was no parentheses solution i.e.
HTML inputs were intended numerical values for variables a and b, so say the inputs were 2 and 3.
Following gave string concatenation outputs: a+b displayed 23; +a+b displayed 23; (a)+(b) displayed 23;
From suggestions above we tried successfully : Number(a)+Number(b) displayed 5; parseInt(a) + parseInt(b) displayed 5.
Thanks for the help just an FYI - was very confusing and I his Dad got yelled at 'that is was Blogger.com's fault" - no it's a feature of HTML input default combined with the 'addition' operator, when they occur together, the default left-justified interpretation of all and any input variable is that of a string, and hence the addition operator acts naturally in its dual / parallel role now as a concatenation operator since as you folks explained above it is left-justification type of interpretation protocol in Java and Java script thereafter. Very interesting fact. You folks offered up the solution, I am adding the detail for others who run into this.
Simple as easy ... every input type if not defined in HTML is considered as string. Because of this the Plus "+" operator is concatenating.
Use parseInt(i) than the value of "i" will be casted to Integer.
Than the "+" operator will work like addition.
In your case do this :-
divID = "question-" + parseInt(i)+1;