This question already has answers here:
How to convert a string to an integer in JavaScript
(32 answers)
What is the purpose of a plus symbol before a variable?
(4 answers)
Closed 4 years ago.
Can anyone tell me why and how the expression 1+ +"2"+3 in JavaScript results in 6 and that too is a number? I don't understand how introducing a single space in between the two + operators converts the string to a number.
Using +"2" casts the string value ("2") to a number, therefore the exrpession evaluates to 6 because it essentially evaluates to 1 + (+"2") + 3 which in turn evaluates to 1 + 2 + 3.
console.log(1 + +"2" + 3);
console.log(typeof "2");
console.log(typeof(+"2"));
If you do not space the two + symbols apart, they are parsed as the ++ (increment value) operator.
It's simple first it convert the string +"2" to number(According to the operator precedence) and then add all these.
For Operator precedence mozilla developer link
1+ +"2"+3 results 6
1+"2"+3 results "123"
AS The unary + operator converts its operand to Number type.
+"2" is a way to cast the string "2" to the number 2. The remain is a simple addition.
The space between the two + operators is needed to avoid the confusion with the (pre/post)-increment operator ++.
Note that the cast is done before the addition because the unary operator + has a priority greater than the addition operator. See this table: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table
Related
This question already has answers here:
Why does JavaScript handle the plus and minus operators between strings and numbers differently?
(7 answers)
Closed 3 years ago.
I was trying to subtract the last digit out of a string after a loop, but then I found this mysterious phenomenon.
When I add two string of numbers, they concatenate:
"1" + "1" // = "11"
But when I subtract a string of number from another, it did not decatenate but was casted as a number instead:
"11" - "1" // = 10
Why does this happen?
Should the result of the subtraction be "1" instead of 10?
Wouldn't having some kind of consistency be better?
Edit: This question is NOT a duplicate of the question below, as this question is asking about the subtraction of two strings, instead of a string with a number.
Why does JavaScript handle the plus and minus operators between strings and numbers differently?
The subtraction operator (-) subtracts the number to the right of the
operator from the number on the left.
When either of the operands are strings, an attempt is made to convert
the strings to numbers.
Source
This question already has answers here:
Why does JavaScript handle the plus and minus operators between strings and numbers differently?
(7 answers)
Adding and subtracting strings and numbers in Javascript - auto type conversion?
(5 answers)
Closed 5 years ago.
What will be an output of:
var number = "1.2";
console.log(number - 0.2);
console.log(number + 0.2);
And why?
The answer will be
1 and
1.20.2 respectively
Note that number is string, but since - operator is not supported by string, JS converts it to number thus the output 1. for the second case, since + operator is supported by string, it will simply concatenate it, hence the answer 1.20.2
The output is
1
1.20.2
Why ?
In the first case the variable string is converted to number because there is no - operator for strings
But there is a + operator for string and it make a concatenation of string, it is in the second case prefered to first convert into number
This question already has answers here:
The + + operator in javascript
(2 answers)
Closed 5 years ago.
Why does this statement 1+ +"2"+3 returning 6 in javascript?
console.log(1+ +"2"+3) // 6.
Between the two plus (+) operands there is a single space. Even though we have a quoted string it's treating the string as a number, which is confusing to me.
Can someone please explain this?
Because the + in +"2" coerces "2" to 2, thus you get 1 + 2 + 3, thus 6. The unary¹ + has higher precedence than the binary² + (e.g., it happens first). MDN has a reasonably good precedence chart here.
E.g., starting with 1 + +"2" + 3, then:
The +"2" part is done first, resulting in 2 because that unary + converts the string to number (the same way Number("2") would). So now we have 1 + 2 + 3.
1 + 2 is done next because the binary + operator (whether addition or concatenation) is left-to-right associative. So that gives us 3 and we have 3 + 3 left.
3 + 3 is done, giving us 6.
E.g.:
1 + +"2" + 3
1 + 2 + 3
3 + 3
6
¹ A "unary" operator is an operator accepting only one operand, e.g. the + in +"2" (where "2" is the operand)
² A "binary" operator is an operator accepting two operands, e.g. the + in 1 + 2 (where 1 and 2 are the operands)
(There are also "ternary" operators which accept three operands; JavaScript's only current ternary operator is the conditional operator: test ? result1 : result2)
This question already has answers here:
Why does JavaScript handle the plus and minus operators between strings and numbers differently?
(7 answers)
Closed 5 years ago.
Why does Javascript give an output of 0 when I use the odd operator?
What is the difference between subtraction and addition with a string?
var x = 1;
console.log(x+'1') // Outputs 11
console.log(x-'1') // Outputs 0 -- but why?
So how can I do mathematical calculations?
The + operator has one of two three meanings in javascript. The first is to add numbers, the second is to concatenate strings. When you do 1 + '1' or '1' + 1 the operator will convert one operand that is not a string to a string first, because one other operand is already evaluated to be a string. The - operator on the other hand has just one purpose, which is to subtract the right operand from the left operand. This is a math operation, and so the JS engine will try to convert both operands to numbers, if they are of any other datatype.
I'm not sure though why typecasting to strings appears to have precedence over typecasting to numbers, but it obviously does.
(It seems to me the most likely that this is a pure specification decision rather than the result of other language mechanics.)
If you want to make sure that the + operator acts as an addition operator, you can explicitly cast values to a number first. Although javascript does not technically distinguish between integers and floats, two functions exist to convert other datatypes to their number equivalents: parseInt() and parseFloat() respectively:
const x = 10;
const result = x + parseInt('1'); // 11
const y = 5;
const result2 = y + parseFloat('1.5'); // 6.5
const result3 = y + parseInt('1.5'); // 6
Edit
As jcaron states in the comment below, the + operator has a third meaning in the form of an unary + operator. If + only has a right operand, it will try to convert its value to a number almost equivalent as how parseFloat does it:
+ '1'; // returns 1
+ '1.5'; // returns 1.5
// In the context of the previous example:
const y = 5;
const result2 = y + +'1.5'; // 6.5
Dhe difference with parseFloat is that parseFloat will create a substring of the source string to the point where that substring would become an invalid numeric, whereas unary + will always take the entire string as its input:
parseFloat('1.5no-longer-valid'); // 1.5
+ '1.5no-longer-valid'; // NaN
That is because + is a concatenation operator. So javascript considers it to be a concatenation operator rather than a mathematical operator.But it is not the case with / ,* ,/ etc.
This happens because + its also used to concatenate strings. Then, JS always will find the better way to make the correct typecasts basing on types. In this case, the x+'1' operation, will be identified as string type + string type.
Otherwise, x-'1', will become int type - int type.
If you want to work with specific types, try to use type cast conversions, link here.
This question already has answers here:
What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012?
(5 answers)
Closed 9 years ago.
Some operations in javascript returns unexpected results. One is extremely strange:
[] + 1 = "1"
Can anybody explain why it works like that?
[] are converted to an empty string due to + operator. so "" + 1 => "1" (number converted to string too)
Javascript's rules for addition between differeent types are as follows:
Given the following addition.
value1 + value2
To evaluate this expression, the following steps are taken (§11.6.1):
Convert both operands to primitives (mathematical notation, not JavaScript):
prim1 := ToPrimitive(value1)
prim2 := ToPrimitive(value2)
PreferredType is omitted and thus Number for non-dates, String for dates.
If either prim1 or prim2 is a string then convert both to strings and return the concatenation of the results.
Otherwise, convert both prim1 and prim2 to numbers and return the sum of the results.
Source
In this case the array gets converted to an empty string, and then the + performs string concatenation
ECMAScript 11.6.1 defines addition. Steps 5 and 6 of addition call ToPrimitive (9.1) for each operand and operate on those results:
For an array (or any object), ToPrimative calls the toString method of the object. The result of calling toString on an empty array is the empty string (per the behavior described in 15.4.4.2.
For a number, ToPrimitive returns the number (since numbers are already primitive).
We're left adding the empty string and the number 1. When either operand in addition is a string, the addition acts as a concatenation operation (per addition's step 7), so we end up with "" + "1" = "1".