Different Javascript behavior on substraction and sum [duplicate] - javascript

This question already has answers here:
Javascript addition and subtraction with a string value
(8 answers)
Closed 8 years ago.
Why such thing would happen in Javascript?
'5'+3 = 53
'5'-3 = 2

This is happening because + operator is overloaded. If any operand is a string, string concatenation is performed. If you have two numbers, addition is performed.
In other words
2+3=5
while '2'+3='23' and 2+'3'='23'.
On the other hand, for the - operator, it is not overloaded in such a way and all operands are converted to numbers.
'8'-2=6
because - is not overloaded and operand '8' will be converted to 8. Hence, we get 6.
For further information on this, please have a look here and read the paragraphs 11.6.1 and 11.6.2.

String concatenation is done with + so Javascript will convert the first numeric 5 to a string and concatenate "5" and "3" making "53".
You cannot perform subtraction on strings, so Javascript converts the second numeric i.e. "3" to a number and subtracts 3 from 5, resulting in "2" as the result.

Related

How I am getting Output = 1 for console.log('6'/'6') in Javascript. It should not be able to devide two strings [duplicate]

This question already has answers here:
using division operator (/) on strings in javascript
(3 answers)
Closed last year.
Check the code Image
How I am getting Output = 1 for console.log('6'/'6') in Javascript. It should not be able to devide two strings
When a mathematical operator that only makes sense on numbers is applied to two expressions, both expressions are coerced to numbers first..
4. Let lnum be ? ToNumeric(lval).
5. Let rnum be ? ToNumeric(rval).
7. 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
...
which then calls Number::divide with lnum and rnum.
The only exception is +, which will only add if both sides are numbers - otherwise, it will coerce both sides to strings and then concatenate.

Weird add many Char in javascript [duplicate]

This question already has answers here:
Why is the result of ('b'+'a'+ + 'a' + 'a').toLowerCase() 'banana'?
(8 answers)
Closed 3 years ago.
Today i saw an example of JavaScript and i can not understand it.
('b' + 'a' + + 'a' + 'a').toLowerCase()
result: "banana"
I don't understand it, why JavaScript add 2 'n' between each 'a'?
The first ‘b’ and ‘a’ are simply strings being added as ‘ba’. After the second ‘a’, you see a double plus sign(+), the first one is for concatenation like the previous plus sign. But the second plus sign is called the unary operator which simply transforms the string into a number, if it isn’t already. Since ‘a’ cannot be converted to a number it is converted to ‘NaN’. The final ‘a’ is added to this ‘baNaN’ string and the final ‘baNaNa’ string is made. And to finish it up, the toLowerCase function is used and the output ‘banana’ is received.

JS Preserve decimals ending in zeroes [duplicate]

This question already has answers here:
How can I round a number in JavaScript? .toFixed() returns a string?
(16 answers)
Convert 0 to 0.00 as number
(1 answer)
Is there any way to maintain an integer with .00 in javascript?
(1 answer)
Closed 3 years ago.
In JavaScript, is it possible to "lock" a decimal number, to preserve "floating point" numbers that end with zeroes?
Example, I have 2 different numbers, like this: (pseudo code)
let a = 1.0;
let b = 1.00;
a === b // true, should be false, because different decimals.
print(a) // "1", should be "1.0"
print(b) // "1", should be "1.00"
(should also be different from a "true int" 1)
I want them to identify as different from each other, because they have different amount of zeroes at the end.
But stupidly "efficient" JavaScript rounds them both down to "integer" 1 & therefore they are equal.
I am aware of the Number.toFixed(Number) & Number.toPrecision(Number) functions, but to use them like this I have to first calculate the length of the number, which I can't because JavaScript have already rounded away the zeroes.
I have also been thinking of "cutting" off the number at the decimal point & store them in an array... but again, rounded to an "int" without a decimal point.
(Yes, I know that the concept of "float" doesn't exist in JS, I use it here to diferentiate between numbers with or without decimals).
Thanks for any help.
To compare 2 variables of indefinite type, the variables must be cast internally. This is the problem. Because both A and B are a set with the thickness 1.
Therefore the result is True.
However, if you want to compare the number of zeros, you have to compare them as a string.
So either you declare the variables with
let a = '1.0';
let b = '1.00';
or you cast the variables using
a.toString() === b.toString();

Is there any reason not to use the plus operator instead of Number() or parseInt() to return a number? [duplicate]

This question already has answers here:
parseInt vs unary plus, when to use which?
(6 answers)
What is the difference between parseInt() and Number()?
(11 answers)
Closed 4 years ago.
Basically, I'm trying to figure out what the difference is between these 3 statements? Is there any reason to use one instead of the others? Is the first one bad practice (it works but I never see it and doesn't seem to be taught anywhere)?
+'21';
Number('21');
parseInt('21');
parseInt parses the string up to the first non-digit number and returns what it found,
For example: parseInt('123abc') // returns 123;
Number tries to convert the entire string into a number if it can.
ForExample: Number('123abc') // returns NaN
Unary plus operator can also be used to convert a string into a number, but it is not very readable when it is being used with other expressions and operators
Internally, +'21' will work in the same way as Number('21') * 1
As far as I know the first two are completely equivalent, and the choice between them is a matter of taste. (Personally I prefer the unary + because it's more concise, and well understood by most JS developers.)
parseInt is different because it reads a number value from the start of the string and ignores the rest when it reaches a non-numeric character. A common use is getting the underlying number from a CSS value like "20px". Note that the other two methods would fail with a NaN in this case.

Leading zeros leading to wrong sorting answer using inbuilt sort method of javascript [duplicate]

This question already has answers here:
Javascript - Leading zero to a number converting the number to some different number. not getting why this happening?
(2 answers)
Closed 5 years ago.
I was sorting a string/array of integers in lexicographical order. A case came when i had to sort a string containing "022" using array.sort. I don't know why it is equating that equal to "18" when being printed.
var l = [022,12];
l.sort();
(2) [12, 18] => output
What is the reason behind this and how to correct it?
I recommend to "use strict"; so that 022 will produce a syntax error instead of octal number:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Deprecated_octal
This isn't specific to the sort. If you just type 022 into a console, you'll get back 18. This is because 022 is being interpreted as an OctalIntegerLiteral, instead of as a DecimalLiteral. This is not always the case however. Taking a look at the documentation:
Note that decimal literals can start with a zero (0) followed by another decimal digit, but If all digits after the leading 0 are smaller than 8, the number is interpreted as an octal number. This won't throw in JavaScript, see bug 957513. See also the page about parseInt().
EDIT: To remove the leading 0s and interpret the 022 as a decimal integer, you can use parseInt and specify the base:
parseInt("022", 10);
> 22

Categories

Resources