I have seen code where strings were casted to numbers using the plus operator.
This would look something like:
var x ="5",y;
y = +x;
console.log(typeof y) //number
How does this work?
In fact, there are two + operators : the binary + operator and this one : the Unary + operator.
See how it's described in the MDN :
(Unary Plus)
The unary plus operator precedes its operand and evaluates to its
operand but attempts to converts it into a number, if it isn't
already. For example, y = +x takes the value of x and assigns that to
y; that is, if x were 3, y would get the value 3 and x would retain
the value 3; but if x were the string "3", y would also get the value
3. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a
number, because it does not perform any other operations on the
number. It can convert string representations of integers and floats,
as well as the non-string values true, false, and null. Integers in
both decimal and hexadecimal ("0x"-prefixed) formats are supported.
Negative numbers are supported (though not for hex). If it cannot
parse a particular value, it will evaluate to NaN.
var x = "5",
y;
You're declaring two variables named respectively x and y. The former is set to hold the string "5", the latter holds the undefined value(since it's declared but not defined).
Then you're setting y to be the conversion in Number type of the string "5"(via the unary operator +), which is 5. So you're getting typeof y to be number.
The + operator is the unary operator. It evaluates an object trying to convert it into a number.
Related
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:
Why does JavaScript handle the plus and minus operators between strings and numbers differently?
(7 answers)
Closed 7 years ago.
I read a book about operators in Javascript, and this confused me.
console.log("5"+1);
This would make "5" as a string. So the result would be 51.
console.log("5"-1);
This result would be 4. I know it converts "5" to 5, but why it isn't shown undefined as "a string minus a number"?
Update: So how about other languages? Are they more restrict?
Sadly, it was expected from JavaScript to ride on Java's success for promotion on its early days and the plus for string concatenation was adopted since Java used it.
So JavaScript tries hard to coerce strings into numbers for you, it really does, its just that the plus was taken for strings so....well...
While Javascript has many strenghts it was made in 10 days and has many hilarious aspects like this one, check this comedy gold
The + is a operator that means SUM when adding numbers and that means CONCATENATE when using Strings.
As the first is a STRING, it will continue concatenating a "5"+toString(1).
As the MINUS (-) operator does not work with String you are getting undefined.
If you want to use MINUS operator, you will need to do :
parseInt("5") -> It will give you 5, the number
parseInt("5")-1 = 4
"5"+1 = 51
parseInt("5")+1 = 6
Hope it will help you
Because when we use '+' it can be used in two different ways:-
1. as mathematical operator.
2. to concatenate strings
but '-' can only be used as mathematical operator.
Hence javascript considers '5' as numerics in case of '-' while '5' as string in case of '+'.
In javascript (+) operator operates the way described below
3+true will return 4 , (+) operator between a number and a boolean or two boolean will convert boolean to number , hence true is converted to 1 hence the result is 4
"2"+true will return "2true" , if one of the operand is string it will convert the other operand (number or boolean) to string and process the concatenation
-"12"+3 will return -9 , (-) operator in front of string will convert the string to number and will make it as -12 and return -9
According to the standard EcmaScript 262. The + and - operators behave differently when strings are involved. The first converts every value to a string. The second converts every value to a number.
From the standard:
If Type(lprim) is String or Type(rprim) is String, then Return the
String that is the result of concatenating ToString(lprim) followed by
ToString(rprim)
This rules implies that if in the expression there is a string value, all values involved in the + operation are converted to a string. In JavaScript when the + operator is used with strings, it concatenates them. This is why console.log("5"+1) returns "51". 1 is converted to a string and then, "5" + "1" are concatenated together.
Nevertheless, the above rule doesn't apply for the - operator. When you are using a - all values are converted to numbers according to the Standard (see below). Therefore, in this case, "5" is converted to 5 and then 1 is subtracted.
From the standard:
5 Let lnum be ToNumber(lval).
6 Let rnum be ToNumber(rval).
Operator definition from the standard EcmaScript 262.
Operator + : http://www.ecma-international.org/ecma-262/5.1/#sec-11.6.1
Operator - : http://www.ecma-international.org/ecma-262/5.1/#sec-11.6.2
Because of the type coercion and how it isn't very consistent in JavaScript, in the second case the "5" is converted to a number 5, and 1 is subtracted from it, giving you 4.
"5" could be coerced to 5 (Integer). That's why you get 4 as output.
However if you try:
console.log("text" - 1);
Text cannot be coerced, and the output is NaN
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.
Instead of using "5" if you try console.log("abc" - 1); it will prompt a error as NaN.
Just for the info:
The subtract operator has special rules to deal with the variety of type conversions present in JavaScript:
If the two operands are numbers, perform arithmetic subtract and return the result.
If either number is NaN, the result is NaN.
If Infinity is subtracted from Infinity, the result is NaN.
If –Infinity is subtracted from –Infinity, the result is NaN.
If –Infinity is subtracted from Infinity, the result is Infinity.
If Infinity is subtracted from –Infinity, the result is –Infinity.
If +0 is subtracted from +0, the result is +0.
If –0 is subtracted from +0, the result is –0.
If –0 is subtracted from –0, the result is +0.
If either of the two operands is not a number, the result is NaN.
This question already has answers here:
What is the rationale for all comparisons returning false for IEEE754 NaN values?
(12 answers)
Closed 10 years ago.
Why are these two different?
var x = NaN; //e.g. Number("e");
alert(isNaN(x)); //true (good)
alert(x == NaN); //false (bad)
Nothing is equal to NaN. Any comparison will always be false.
In both the strict and abstract comparison algorithms, if the types are the same, and either operand is NaN, the result will be false.
If Type(x) is Number, then
If x is NaN, return false.
If y is NaN, return false.
In the abstract algorithm, if the types are different, and a NaN is one of the operands, then the other operand will ultimately be coerced to a number, and will bring us back to the scenario above.
The equality and inequality predicates are non-signaling so x = x returning false can be used to test if x is a quiet NaN.
Source
This is the rule defined in IEEE 754 so full compliance with the specification requires this behavior.
The following operations return NaN
The divisions 0/0, ∞/∞, ∞/−∞, −∞/∞, and −∞/−∞
The multiplications 0×∞ and 0×−∞
The power 1^∞
The additions ∞ + (−∞), (−∞) + ∞ and equivalent subtractions.
Real operations with complex results:
The square root of a negative number
The logarithm of a negative number
The tangent of an odd multiple of 90 degrees (or π/2 radians)
The inverse sine or cosine of a number which is less than −1 or greater than +1.
The following operations return values for numeric operations. Hence typeof Nan is a number. NaN is an undefined number in mathematical terms. ∞ + (-∞) is not equal to ∞ + (-∞). But we get that NaN is typeof number because it results from a numeric operation.
From wiki:
I was perusing the underscore.js library and I found something I haven't come across before:
if (obj.length === +obj.length) { ... }
What is that + operator doing there? For context, here is a direct link to that part of the file.
The unary + operator can be used to convert a value to a number in JavaScript. Underscore appears to be testing that the .length property is a number, otherwise it won't be equal to itself-converted-to-a-number.
According to MDN:
The unary plus operator precedes its operand and evaluates to its
operand but attempts to converts it into a number, if it isn't
already. For example, y = +x takes the value of x and assigns that to
y; that is, if x were 3, y would get the value 3 and x would retain
the value 3; but if x were the string "3", y would also get the value
3. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a
number, because it does not perform any other operations on the
number. It can convert string representations of integers and floats,
as well as the non-string values true, false, and null. Integers in
both decimal and hexadecimal ("0x"-prefixed) formats are supported.
Negative numbers are supported (though not for hex). If it cannot
parse a particular value, it will evaluate to NaN.
It's a way of ensuring that obj.length is a number rather than a potential string. The reason for this is that the === will fail if the length (for whatever reason) is a string variable, e.g. "3".
It's a nice hack to check whether obj.length is of the type number or not. You see, the + operator can be used for string coercion. For example:
alert(+ "3" + 7); // alerts 10
This is possible because the + operator coerces the string "3" to the number 3. Hence the result is 10 and not "37".
In addition, JavaScript has two types of equality and inequality operators:
Strict equality and inequality (e.g. 3 === "3" expresses false).
Normal equality and inequality (e.g. 3 == "3" expresses true).
Strict equality and inequality doesn't coerce the value. Hence the number 3 is not equal to the string "3". Normal equality and inequality does coerce the value. Hence the number 3 is equal to the string "3".
Now, the above code simply coerces obj.length to a number using the + operator, and strictly checks whether the value before and after the coercion are the same (i.e. obj.length of the type number). It's logically equivalent to the following code (only more succinct):
if (typeof obj.length === "number") {
// code
}
var a = "ab";
var b = "ab";
a+=1; // "ab1"
b++; // "NaN"
(Tested on chrome's V8)
Can someone explain why the results are different based on the internal atomic actions of the ++ arithmetic operator and the += assignment operator with argument 1
++ converts to number, and then increments, += with a String concatenates.
From the spec:
11.3.1 Postfix Increment Operator
...
3. Let oldValue be ToNumber(GetValue(lhs)).
4. Let newValue be the result of adding the value 1 to oldValue, using the same rules as for the + operator (see 11.6.3).
For the a+=1 case, if you add a number to a string or the other way around the number gets converted to a string:
11.6.1 The Addition operator ( + )
...
7. If Type(lprim) is String or Type(rprim) is String, then
a. Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
8. Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim).
++ tries to increment a Number (if it's not a number, this will fail - resulting in NaN)
+= is concatenation, in this case the JavaScript engine figures out that one side is a string, so they're both concatenated as strings.
They're different because they're different operations, ++ is specifically an arithmetic operator, where as += is a more general assignment operator that behaves differently based on the data type - specifically, string has its own implementation.
That's because the + operator in javascript is both the mathematical + and the string concatenation operator, while the ++ is always a mathematical operator.
So, when you have:
string = string + number;
the number is converted to string and concatenated to the first string.
When you have
string++
you will convert the string to a number, getting NaN, and then add one to that - getting still, NaN.