Hi i have a javascript code like this
var a=10;
var b="100";
document.write(b-a);
Actually it should show an error when we are subtracting a number from a string but it is showing as 90 as output but when we do b+a it is showing 10010 as output what is this behaviour.
the - operator in JavaScript only applies to math, so your vars are both converted to numbers. You'll only get an error (or more specifically NaN) if you try to do invalid math, e.g. 100 - 'a'. The + operator is valid for both strings and numbers, so its behavior changes:
If both vars are numbers, mathematical additions is used
otherwise string concatenation is used
When you subtract, Javascript attempts to cast the String b to Number, because there is no - operation defined for String.
When you use the + sign, Javascript attempts to cast the Number a to a String, because + is defined as concatenation for a String.
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.
I have just observed that the parseInt function doesn't take care about the decimals in case of integers (numbers containing the e character).
Let's take an example: -3.67394039744206e-15
> parseInt(-3.67394039744206e-15)
-3
> -3.67394039744206e-15.toFixed(19)
-3.6739e-15
> -3.67394039744206e-15.toFixed(2)
-0
> Math.round(-3.67394039744206e-15)
0
I expected that the parseInt will also return 0. What's going on at lower level? Why does parseInt return 3 in this case (some snippets from the source code would be appreciated)?
In this example I'm using node v0.12.1, but I expect same to happen in browser and other JavaScript engines.
I think the reason is parseInt converts the passed value to string by calling ToString which will return "-3.67394039744206e-15", then parses it so it will consider -3 and will return it.
The mdn documentation
The parseInt function converts its first argument to a string, parses
it, and returns an integer or NaN
parseInt(-3.67394039744206e-15) === -3
The parseInt function expects a string as the first argument. JavaScript will call toString method behind the scene if the argument is not a string. So the expression is evaluated as follows:
(-3.67394039744206e-15).toString()
// "-3.67394039744206e-15"
parseInt("-3.67394039744206e-15")
// -3
-3.67394039744206e-15.toFixed(19) === -3.6739e-15
This expression is parsed as:
Unary - operator
The number literal 3.67394039744206e-15
.toFixed() -- property accessor, property name and function invocation
The way number literals are parsed is described here. Interestingly, +/- are not part of the number literal. So we have:
// property accessor has higher precedence than unary - operator
3.67394039744206e-15.toFixed(19)
// "0.0000000000000036739"
-"0.0000000000000036739"
// -3.6739e-15
Likewise for -3.67394039744206e-15.toFixed(2):
3.67394039744206e-15.toFixed(2)
// "0.00"
-"0.00"
// -0
If the parsed string (stripped of +/- sign) contains any character that is not a radix digit (10 in your case), then a substring is created containing all the other characters before such character discarding those unrecognized characters.
In the case of -3.67394039744206e-15, the conversion starts and the radix is determined as base 10 -> The conversion happens till it encounters '.' which is not a valid character in base 10 - Thus, effectively, the conversion happens for 3 which gives the value 3 and then the sign is applied, thus -3.
For implementation logic - http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.2.2
More Examples -
alert(parseInt("2711e2", 16));
alert(parseInt("2711e2", 10));
TO note:
The radix starts out at base 10.
If the first character is a '0', it switches to base 8.
If the next character is an 'x', it switches to base 16.
It tries to parse strings to integers. My suspicion is that your floats are first getting casted to strings. Then rather than parsing the whole value then rounding, it uses a character by character parsing function and will stop when it gets to the first decimal point ignoring any decimal places or exponents.
Some examples here http://www.w3schools.com/jsref/jsref_parseint.asp
parseInt has the purpose of parsing a string and not a number:
The parseInt() function parses a string argument and returns an
integer of the specified radix (the base in mathematical numeral
systems).
And parseInt calls the function ToString wherein all the non numerical characters are ignored.
You can use Math.round, which also parses strings, and rounds a number to the nearest integer:
Math.round("12.2e-2") === 0 //true
Math.round("12.2e-2") may round up or down based on the value. Hence may cause issues.
new Number("3.2343e-10").toFixed(0) may solve the issue.
Looks like you try to calculate using parseFloat, this will give you the correct answer.
parseInt as it says, returns an integer, whereas parseFloat returns a floating-point number or exponential number:
parseInt(-3.67394039744206e-15) = -3
parseFloat(-3.67394039744206e-15) = -3.67394039744206e-15
console.log('parseInt(-3.67394039744206e-15) = ' , parseInt(-3.67394039744206e-15));
console.log('parseFloat(-3.67394039744206e-15) = ',parseFloat(-3.67394039744206e-15));
Why does x = "1"- -"1" work and set the value of x to 2?
Why doesn't x = "1"--"1" works?
This expression...
"1"- -"1"
... is processed as ...
"1"- (-"1")
... that is, substract result of unary minus operation applied to "1" from "1". Now, both unary and binary minus operations make sense to be applied for Numbers only - so JS converts its operands to Numbers first. So that'll essentially becomes:
Number("1") - (-(Number("1"))
... that'll eventually becomes evaluated to 2, as Number("1"), as you probably expect, evaluates to 1.
When trying to understand "1"--"1" expression, JS parser attempts to consume as many characters as possible. That's why this expression "1"-- is processed first.
But it makes no sense, as auto-increment/decrement operations are not defined for literals. Both ++ and -- (both in postfix and prefix forms) should change the value of some assignable ('left-value') expression - variable name, object property etc.
In this case, however, there's nothing to change: "1" literal is always "1". )
Actually, I got a bit different errors (for x = "1"--"1") both in Firefox:
SyntaxError: invalid decrement operand
... and Chrome Canary:
ReferenceError: Invalid left-hand side expression in postfix operation
And I think these messages actually show the reason of that error quite clearly. )
Because -- is an operator in JavaScript.
When you separate the - characters in the first expression, it's unambiguous what you mean. When you put them together, JavaScript interprets them as one operator, and the following "1" as an unexpected string. (Or maybe it's the preceding "1"? I'm honestly not sure.)
"-1" = -1 (unary minus converts it to int)
So. "1" - (-1)
now, "+" is thje concatenation operator. not -. so JS returns the result 2 (instead of string concat).
also, "1"--"1" => here "--" is the decrement operator, for which the syntax is wrong as strings will not get converted automatically in this case.
because -- is an operator for decrement and cannot be applied on constant values.
In JavaScript, can someone explain the results of the 2 following expressions:
"4" + 4 and 4 + "4"
Thanks!
Both will result in the String:
"44"
This is because the + operator serves 2 purposes -- addition and concatenation. And, if either operand is a String (or is cast to a String by the internal ToPrimitive()) they'll be concatenated.
This is described in the specification as:
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). See the Note below 11.6.3.
If you want to ensure addition, you can use parseFloat() or the unary + on each:
var a = "4", b = 4;
console.log(parseFloat(a) + parseFloat(b)); // 8;
console.log((+a) + (+b)); // 8, extra parenthesis for clarity
1+'1'+1 = '111'
1+1+'1' = '21'
'1'+(1+1) = '12'
'1'+1+1 = '111'
Javascript performs math until it hits a string and then switches to concatenation, and it also follows regular formula rules run () operations first.
they'll both be '44'. The presence of the '4' as a string casts the whole operation to a string, so the two characters are concatenated.
Cited from: http://javascript.about.com/od/variablesandoperators/a/vop10.htm
One thing that can be confusing to beginners is that JavaScript uses +
with text strings to mean something completely different from what it
means with numbers. While with numbers + means add the numbers
together with text + means concatenate them together. Concatenation
basically means joining one text string onto the end of the first so
that "my"+"book" gives "mybook" as a result. Where beginners tend to
get confused is that while 3+3 gives 6, "3"+"3" gives "33".
You can also use += with text strings to directly add the variable or
text on the right onto the end of the text string variable on the
left.
Mixing Data Types
Additional confusion can arise when you are working with variables
that are of different types. All operations require that the variables
that they are operating on both be of the same type. Before JavaScript
is able to perform any operations that involve two different data
types, it must first convert one of the variables from one type to the
other. You can't add a number to a text string without first either
converting the number to text or the text to a number.
When converting between data types we have two choices. We can allow
JavaScript to do the conversion for us automatically or we can tell
JavaScript which variable that we want to convert.
JavaScript will attempt to convert any text string into the number
equivalent when performing subtraction, multiplication, division, and
taking remainders. Your text string will actually need to contain
something that JavaScript can convert to a number (i.e., a string like
"10") in order for the conversion to work.
If we use + then this could either mean that we want to convert the
string to a number and add then or that we want to convert the number
to a string and concatenate them. JavaScript can only perform one of
these two alternatives. It always converts numbers to strings (since
that will work whether the string contains a number or not).
Here are some examples.
"5" - 3 = 2;
"5" + 3 = "53"
2 + "7" = "27"
5 + 9 + "1" = "141"
Since subtraction only works with numbers 1 converts the text string
into a number before doing the subtraction.
In 2 and 3 the number is converted to a text string before being
concatenated (joined) to the other text string.
In 4 the leftmost addition is done first. Since these are both numbers
they are actually added together and not treated as text. The result
of this first addition leaves us with a similar situation to the third
example and so the result of that addition is converted to text and
concatenated.
To actually force JavaScript to convert a text string to a number we
can use Number("3") or alternatively to force JavaScript to convert a
number to a text string we can use String(5).
Expressions in JS work on two prime principles.
B O D M A(includes concat) S
Left to right order of execution
However, its not straight forward
for + operator
as far as it encounters numbers it will do math addition using left to right execution, However,as soon as it encounters a string, it concatenates the result (that's calculated till encountering a string) with rest of the expression.
//left to right execution
console.log(10+10+"10") //2010, (10+10) of numtype + "10" of stringtype concat(20+"10")
console.log(10+10+"10"+10+10) //20101010,
//(10+10) of number type + "10" stringtype(now since a string is enc.) + (10+10) of number type would act as strings and get concatenated = 20+"10"+"1010"
console.log("10"+[10,10,10]+10) //1010,10,1010
//"10"of stringtype + array of numtypes + 10 of numtype
// "10" concats with first element of array, last number 10 concats with last element of array.
for all other operators such as -,*,/,^...
if all occurrences are numbers/numbers as string, it will do the respective math operation treating "numbers as string" to be numbers.
console.log("10"-10) //0
console.log("10"/10) //1
console.log("10"*10) //100
console.log(10+"10"*10) //110 //BODMAS
console.log(Math.pow(10,"10")) //10000000000
if there are occurrences of non-numeric strings,arrays,objects in the middle of expression that involve (-,*,/,^...)math operations, it will always return NaN
console.log(10-{id:1,name:"hey"}-10) //NaN
console.log(10-10-"hey"-10-10-10) //NaN
console.log("hey"/10) //NaN
console.log("hey"* 3) //NaN
console.log(["hey","hey"]*"3") //NaN
console.log("10"/[10,10,10]/10) //NaN
I am puzzled by this snippet:
var n1 = 5-"4";
var n2 = 5+"4";
alert(n1);
alert(n2);
I understand that n1 is 1. That is because a minus operator would convert the string "4" into number and subtract it from 5.
But why do we get 54 in case of + operator?
Can someone explain this difference between + and = operators to me?
By type conversion any + expression, that contains a strings, will result in a string. Thus all operands (in your case 5) will be converted to a string, before executing the concatenation.
- on the other hand is just an arithmetic operand, thus "4" is converted to an integer and the calculation is performed as you expect.
It's because in n2, + is being treated as concatenation, not addition. So 5 is converted to the string "5" and "4" is concatenated, giving "54".
When there's a string in either side of +, the + will be considered as a string concatenating operator, the other side will be converted to string and then do the concatenating.
And be careful of something like 1+2+'3', the result is '33' rather than '123'.
- operator has only one meaning - numbers subtraction (or negation and in that case, also conversion to number). In case of + operator, however, there are two: number addition and strings concatenation. When one of the operands of + operator is a string it does string concatenation instead of numbers addition.
The entire process is a bit more complicated than that though and involves an algorithm that you can learn a bit more here, for example.
The + operator is also a string operator. Quite every basic type variable in javascript can be interpreted also in its string representation. You are just attaching 5 to 4 getting 54.
The - operator is not a string operator so the compiler tries to interpret "4" as a number, thus getting 1
Javascript takes 5 as a number and "4" as string.
The javascript + operator use to concat two things.
If you want to addition please use parseInt.
var n1 = 5-"4";
var n2 = parseInt(5)+parseInt("4");
alert(n1);
alert(n2);