Why is string number addition not coalescing intuitively [duplicate] - javascript

This question already has answers here:
Autoconversion in javascript: Isn't it supposed to convert a string to a number when done like stringvar = 1+stringvar?
(2 answers)
Adding and subtracting strings and numbers in Javascript - auto type conversion?
(5 answers)
Why does JavaScript handle the plus and minus operators between strings and numbers differently?
(7 answers)
Closed 1 year ago.
Why is the last operation returning 20?
console.log(2 + 2); // equals 4
console.log("2" + "2"); // equals "22"
console.log(2 + 2 - 2); // equals 2
console.log("2" + "2" - "2"); // equals 20

+ and - evaluate left-to-right. When either operand is a string, the result is concatenation. When both are numbers, the result is addition.
In contrast, - will always coerce both sides to numbers.
'2' + '2' - '2'
does
// left-to-right
('2' + '2') - '2'
// both sides are strings, so concatenate
'22' - '2'
// operator is -, so coerce both sides to numbers
22 - 2
20

The signs + and - work very differently in string concatenation. The + operator gives direct concatenation instructions on strings whereas the - operator tries to coerce the types and perform the mathematical function.
console.log("2" + "2");
console.log(typeof ("2" + "2"));
console.log("2" - "2");
console.log(typeof("2" - "2"));

Related

Why '1' + '2' - 3 gives 9? [duplicate]

This question already has answers here:
How to force JS to do math instead of putting two strings together [duplicate]
(11 answers)
Closed 1 year ago.
I am new to javascript, and I tried to run the below in Brave browser:
'1' + '2' - 3;
The browser replied with the value 9, which I don't understand.
'1' + '2' is concatenation of strings and result is '12'.
'12' - 3 is math operation 12 - 3 and result is 9.
You shoud do the intermediate steps and see for yourself.
Try:
a = '1' + '2';
console.log(a);
b = a - 3;
console.log(b); // prints 9
The + operator is described as for purpose of sum of numeric operands or string concatenation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Addition
That is because your first two numbers are strings. you would get a correct answer if you used:
1 + 2 - 3
Or if you cannot avoid doing a calculation on a string, convert it to a number first:
parseInt('1') + parseInt('2') - 3
'1'+ '2' = '12' is a string but it is converted to an integer before being substracted by -3, so 12-3.

What is the explanation for typeof a where var a = 2 + [] is string?

I am looking at the typeof a where var a = 2 + []. I expected the answer to be 2 of type number but I am getting '2' of type string. However, when I evaluate var b = 2 - [], I get the value to be 2 of type number. Can somebody assist me to understand this behavior.
const arr = [];
const a = 2 + arr;
console.log(a); // '2'
console.log(typeof a) // string
const b = 2 - arr;
console.log(b) // 2
console.log(typeof b); // number
//I expected the value a to be 2 of type
//number just as b
//If I toggle the boolean value of arr,
//both a and b evaluates to 2 of
//type number
+ with two operands is the "addition operator," which may do mathematical addition or string addition (concatenation) depending on its operands.
When any operand to + is an object, the JavaScript engine converts the object to a primitive. In your case, the array is an object. Converting an array to a primitive yields a string (as though you'd called their toString method, which basically does .join()). So then the + operator is dealing with a number and a string. When either operand is a string, + converts the other operand to string, and so you get "2" as the result. That is:
2 + [] becomes
2 + "" which becomes
"2" + "" which is
"2"
- with two operands is the "subtraction operator" and it's very different. It's only for math, it doesn't have any string meaning. That means it converts its arguments to numbers. Converting an array to number involves first converting it to a string, then converting the string to a number. [] becomes "" which converts to 0. So:
2 - [] becomes
2 - "" which becomes
2 - 0 which is
2

Understanding some Javascript code [duplicate]

This question already has an answer here:
(![]+[])[+[]]... Explain why this works
(1 answer)
Closed 7 years ago.
I came across this Javascript snippet:
var sum = +((!+[] + !![] + !![] + []) + (!+[] + !![] + !![] + !![] + !![] + !![]));
This example evaluates to 36.
What is happening here and what's the best way to understand/read it?
!! is a way to convert to a Boolean being either true or false. A numerical representation for true is 1 and for false it's 0. So for example:
!![] => true => 1
When you convert +[] to a number it goes to 0 (when converted to a Boolean it's false), so !+[] is true. Now lets convert those items:
var sum = +((!+[] + !![] + !![] + []) + (!+[] + !![] + !![] + !![] + !![] + !![]));
var sum = +((true + true + true + []) + (true + true + true + true + true + true));
var sum = +((3 + []) + (6));
Now note (3 + []) => "3", evals to a string. Then the string is concatenated with the number 6:
var sum = +("3" + 6); // "36"
Then finally the +("36") turns the string into a number:
var sum = 36;
There are three major things to undertand in this particular example:
What is the nature and behavior of the unary + operator
What is the nature and behavior of the logical NOT operator
How the aforementioned operators interact with empty arrays
The unary + operator converts its operand (the value to its right) to a number. The logical NOT operator either converts its operand to a boolean, or flips the value if the operand is already a boolean.
Both of these operators initially get the value of the operand before doing anything. So when the operand is an array, we need to understand what the value of the array is.
Lets try a few things first to explore how these operators behave with an array:
+[]; // 0
![]; // false
The + operator gets the value of its operand, and then converts that to a number. The ! operator gets the value of its operand, and then converts that to a boolean.
What if we were to use the ! operator twice, and use the + operator on that resulting value?
!![]; // true
+!![]; // 1
Now we're seeing the ability to create both the number 0, and the number 1. Given this power, we can begin to do some arithmetic (note that I am using the grouping operator for legibility:
(+!![]) + (+!![])
This results in 1 + 1, equaling 2. Performing operations like these enough to achieve 36 would require quite a bit of clutter, but the example above leverages the Addition Operator as a short cut.
The addition operator performs string concatenation, as well as numerical addition. So "foo"+"bar" returns "foobar". Likewise, numbers in string-form will be concatenated, rather than added: "3"+"6" returns "36". The code provided in the question achieves number to string conversion by leveraging the inherent behavior of arrays:
["Hello"].toString(); // "Hello"
[].toString(); // ""
With the addition operator, if any side of the operand is a string, the result will also be a string (see step 7 of 11.6.1). Because the array's .toString method is called, the array produces an empty string. When this string is added to a type of number, a string of that number results:
7 + ""; // "7"
This can be leveraged to concatenate, rather than add, two numbers. In the following example, I adopted our previous code that resulted in 2, and added a couple more grouping operators for legibility:
( ( +!![] ) + [] ) + ( ( +!![] ) + [] ) // "11"
On the left-hand side of the middle + operator we generate the number one, and add it to the string produced by an empty array. We then do the same thing to the value on the right-hand side of the middle + operator. The result, two strings with the value "1". The middle operator then concatenates these two strings, yielding "11".
Given this knowledge, you should be able to revisit the code in your question, and quickly make sense of the individual portions.

understanding js code expression

var PgrtiJr = {
"TWfbR": +((!+[] + !![] + !![] + !![] + []) + (!+[] + !![] + !![]))
};
PgrtiJr.TWfbR -= +((+!![] + []) + (+!![]));
console.log(parseInt(PgrtiJr.TWfbR, 10));
I have above mentioned js code. I executed this code on http://math.chapman.edu/~jipsen/js/. Can anybody explain me how it is equal to 32?
and can you recommend any python library that can evaluate this expression in python
tried execjs but no luck
You need to understand few important things about JavaScript's loose typing. Lets start with simpler things, specific to your question.
An empty array literal is considered truthy, but when you apply unary + operator, the array will be converted to a String and which will then be converted to a number. So, internally +[] evaluates to 0.
console.log(+[]);
// 0
Since [] is truthy, double negating it with logical not operator will give you true, which when used in an arithmetic expression, evaluate to 1, since 1 is loosely equal to true.
console.log(!![], 3 + !![]);
// true 4
Apart from all these, when we use an array literal with + operator, the array will be converted to a string and since one part of the expression is string, the other part of the expression will also be converted to string and string concatenation takes place. So the resulting object will be of type string.
console.log(typeof 1, typeof [], typeof (1 + []), 1 + []);
// number object string 1
With this basic understanding, lets analyze the first expression.
+((!+[]+!![]+!![]+!![]+[])+(!+[]+!![]+!![]))
Lets first take,
(!+[]+!![]+!![]+!![]+[])
Here, +[] evaluates to 0 and logical not makes it as true. Since we use it in an expression with a numeric operand, true is treated as 1. And as per our point 2 seen above, !![] evaluates to 1. So, the expression becomes 1 + 1 + 1 + 1 + [], which is actually 4 + []. And as per point 3, the number 4 will become string 4.
The same way, other part of the expression, (!+[]+!![]+!![]) becomes, 1 + 1 + 1 and which is actually 3. So when you do '4' + 3, you will get '43', which is a string. Now, we have a unary + operator which converts this string to a number. So, the result of evaluation of this expression becomes 43, which is a number.
The other part of the expression,
PgrtiJr.TWfbR -= +((+!![]+[])+(+!![]))
will be evaluated like this
+((1 + []) + 1)
and then
+('1' + 1)
and then
+'11'
which is then evaluated to 11. Since PgrtiJr.TWfbR is actually 43, 43 - 11 becomes 32. That is why you are getting 32 as the answer.
[] is an object that is equal to null.
!![] is a "boolean" that equals to true. (twice ! of null ( = false) )
!+[] is a "boolean" that equals to true.
and if we add a [] after this expressions, they will be converted to string.
so
(!+[]+!![]+!![]+!![]+[]) will be a string that equals 4
(!+[]+!![]+!![]) will be a string that equals 3
hence (!+[]+!![]+!![]+!![]+[]) + (!+[]+!![]+!![]) will be a string that equals 43
and +(!+[]+!![]+!![]+!![]+[])+(!+[]+!![]+!![]) will be a number that again equals 43
in the same way +((+!![]+[])+(+!![])) will equal to 11
so total of expression will equal to 43 - 11 = 32

Convert a string to number with +

Here's an easy one for you true believers: You can use + to convert a string to a number,
var thing = "12"
alert(thing);
alert(typeof thing); // string
thing = +thing;
alert(typeof thing); // number
if (thing == 112) alert("!"); // number
Can someone explain:
What is the name of this process?
How does + convert a string to a number?
Javascript uses a dynamic type system. For me it's a 'cast' operation.
The operator + could be a String operator ('a' + 'b') or an Number operator (1+2). It could be used also between Strings and numbers (remembering that 0 + '12' = 12 and '0'+'12' = '012')
By default, i think that the JS interpreter considered +thing as 0 + things so it casts this variable to a number

Categories