! + [] === true
Can someone explain what's happening here? I understand this is not normal, but I'm struggling to understand what the compiler is doing when it seems operators used in place of variables in mathematical operations.
more examples of this strangeness:
(! + '') === (!'')
but
(! + []) !== (![])
JavaScript always convert inputs to Primitive types. So in your case of ! + [] it will try to convert +[] to string. which will be "" and then because of ! it will convert into boolean. in JavaScript "" is consider as false. So ultimately it will return !false which will be true.
Edit 1
As #mhodges has commented below. [] getting convert to string as "" then + will convert it to number, so it will become 0.
You can learn more about object to primitive from here.
object to primitive
You can check behavior below.
var emptyBrackets = [].toString();
// conversion to string.
console.log(emptyBrackets === '');
// conversion to number.
console.log(+emptyBrackets);
// conversion to boolean.
console.log(!0);
First, it is important to know what operators are being used, and in what order. When this is not clear, an easy way to find out is to look at what the syntax parser makes out of it, e.g. using https://astexplorer.net/, which shows for the first example that:
! + [] === true uses unary logical not (!), unary plus (+), an array literal which is empty ([]), strict equality (===) and the keyword for true (true).
Execution order is (!(+[])) === true, or seen as a tree:
===
/ \
! true
|
+
|
[]
What follows is to understand, what each of the operators are transforming their operands to. This is a bit tedious, when you want to know in detail.
I assume you know what an empty array literal or true produce. Strict equality === is likely also known, as it does not have very many unintuitive aspects (contrary to loose equality ==, which has a LOT). Relevant are therefore only the steps of the unary + and unary logical not.
Given the order of operations, we first look at unary + with [] as operand. It performs ToNumber on the operand, which, for objects like our example [], performs ToPrimitive followed by another ToNumber. ToPrimitive will try valueOf (which will not return a primitive and is therefore not taken), followed by toString. The latter, for arrays, searches for the function join and calls it without arguments (setting the array as this). For an empty array, this results in the empty string "", which will be converted to 0 by the following second call of ToNumber.
Next is the unary logical not, which first transforms any operand with ToBoolean. This intermediary step results in false for our operand 0. Then, as expected, the opposite is being returned (true).
Last but least, as we know, true === true evaluates to true.
An interesting sidenote here is the use of Array.prototype.join in the default case. I would expect many to be surprised, why changes to join would affect the outcome:
console.log(! + [] === true);
let x = [];
x.join = () => "1";
console.log(! + x === true);
Array.prototype.join = () => "1";
console.log(! + [] === true);
The other examples work in a similar way:
(! + '') is almost the same, just that ToNumber does not even need the prior ToPrimitive
For (!''), ToBoolean of an empty string is false, therefore resulting in true
For (![]), ToBoolean of any object is true, resulting in false
Related
I am struggling with understanding how this snippet works on a basic level
if([] == ![]){
console.log("this evaluates to true");
}
Please help me understand where I got it wrong. My thinking:
First there is operator precedence so ! evaluates before ==.
Next ToPrimitive is called and [] converts to empty string.
! operator notices that it needs to convert "" into boolean so it takes that value and makes it into false then negates into true.
== prefers to compare numbers so in my thinking true makes 1 and [] is converted into "" and then 0
Why does it work then? Where did I get it wrong?
Why does it work then?
TLDR:
[] == ![]
//toBoolean [1]
[] == !true
[] == false
//loose equality round one [2]
//toPrimitive([]); toNumber(false) [3]
"" == 0
//loose equality round two
//toNumber("") [4]
0 === 0
true
Some explanations:
1)
First there is operator precedence so ! evaluates before ==
Negating something calls the internal toBoolean method onto that "something" first. In this case this is an Object (as Arrays are Objects) and for that it always returns true which is then negated.
2)
Now it's up to loose equalities special behaviour ( see Taurus answer for more info) :
If A is an Object ( Arrays are Objects ) and B is a Boolean it will do:
ToPrimitive(A) == ToNumber(B)
3)
toPrimitive([])
ToPrimitive(A) attempts to convert its Object argument to a primitive value, by attempting to invoke varying sequences of A.toString and A.valueOf methods on A.
Converting an Array to its primitive is done by calling toString ( as they don't have a valueOf method) which is basically join(",").
toNumber(false)
The result is 1 if the argument is true. The result is +0 if the argument is false. Reference
So false is converted to +0
4)
toNumber("")
A StringNumericLiteral that is empty or contains only white space is converted to +0.
So finally "" is converted to +0
Where did I get it wrong?
At step 1. Negating something does not call toPrimitive but toBoolean ...
The accepted answer is not correct (it is now, though), see this example:
if([5] == true) {
console.log("hello");
}
If everything is indeed processed as the accepted answer states, then [5] == true should have evaluated to true as the array [5] will be converted to its string counterpart ("5"), and the string "5" is truthy (Boolean("5") === true is true), so true == true must be true.
But this is clearly not the case because the conditional does not evaluate to true.
So, what's actually happening is:
1. ![] will convert its operand to a boolean and then flip that boolean value, every object is truthy, so ![] is going to evaluate to false.
At this point, the comparison becomes [] == false
2. What gets into play then is these 2 rules, clearly stated in #6 in the specs for the Abstract Equality Comparison algorithm:
If Type(x) is boolean, return the result of the comparison ToNumber(x) == y.
If Type(y) is boolean, return the result of the comparison x == ToNumber(y)
At this point, the comparison becomes [] == 0.
3. Then, it is this rule:
If Type(x) is Object and Type(y) is either String or Number,
return the result of the comparison ToPrimitive(x) == y.
As #Jonas_W stated, an array's ToPrimitive will call its toString, which will return a comma-separated list of its contents (I am oversimplifying).
At this point, the comparison becomes "" == 0.
4. And finally (well, almost), this rule:
If Type(x) is String and Type(y) is Number,
return the result of the comparison ToNumber(x) == y.
An empty string converted to a number is 0 (Number("") == 0 is true).
At this point, the comparison becomes 0 == 0.
5. At last, this rule will apply:
If Type(x) is the same as Type(y), then
.........
If Type(x) is Number, then
.........
If x is the same Number value as y, return true.
And, this is why the comparison evaluates to true. You can also apply these rules to my first example to see why it doesn't evaluate to true.
All the rules I quoted above are clearly stated here in the specs.
First, realize that you are comparing two different types of values.
When you use ![] it results in false. You have code (at core it results in this):
if([] == false)
Now the second part: since both values are of different type and you are using "==", javascript converts both value type into string (to make sure that they have same type). It starts from left.
On the left we have []. So javascript applies the toString function on [], which results in false. Try console.log([].toString())
You should get false on the left as string value. On the right we have boolean value false, and javascript does the same thing with it.
It use the toString function on false as well, which results in string value false.
Try console.log(false.toString())
This involves two core concepts: how "==" works and associativity of "==" operator - whether it starts from left or right.
Associativity refers to what operator function gets called in: left-to-right or right-to-left.
Operators like == or ! or + are functions that use prefix notation!
The above if statement will result in false if you use "===".
I hope that helps.
This is valid and returns the string "10" in JavaScript (more examples here):
console.log(++[[]][+[]]+[+[]])
Why? What is happening here?
If we split it up, the mess is equal to:
++[[]][+[]]
+
[+[]]
In JavaScript, it is true that +[] === 0. + converts something into a number, and in this case it will come down to +"" or 0 (see specification details below).
Therefore, we can simplify it (++ has precendence over +):
++[[]][0]
+
[0]
Because [[]][0] means: get the first element from [[]], it is true that:
[[]][0] returns the inner array ([]). Due to references it's wrong to say [[]][0] === [], but let's call the inner array A to avoid the wrong notation.
++ before its operand means “increment by one and return the incremented result”. So ++[[]][0] is equivalent to Number(A) + 1 (or +A + 1).
Again, we can simplify the mess into something more legible. Let's substitute [] back for A:
(+[] + 1)
+
[0]
Before +[] can coerce the array into the number 0, it needs to be coerced into a string first, which is "", again. Finally, 1 is added, which results in 1.
(+[] + 1) === (+"" + 1)
(+"" + 1) === (0 + 1)
(0 + 1) === 1
Let's simplify it even more:
1
+
[0]
Also, this is true in JavaScript: [0] == "0", because it's joining an array with one element. Joining will concatenate the elements separated by ,. With one element, you can deduce that this logic will result in the first element itself.
In this case, + sees two operands: a number and an array. It’s now trying to coerce the two into the same type. First, the array is coerced into the string "0", next, the number is coerced into a string ("1"). Number + String === String.
"1" + "0" === "10" // Yay!
Specification details for +[]:
This is quite a maze, but to do +[], first it is being converted to a string because that's what + says:
11.4.6 Unary + Operator
The unary + operator converts its operand to Number type.
The production UnaryExpression : + UnaryExpression is evaluated as follows:
Let expr be the result of evaluating UnaryExpression.
Return ToNumber(GetValue(expr)).
ToNumber() says:
Object
Apply the following steps:
Let primValue be ToPrimitive(input argument, hint String).
Return ToString(primValue).
ToPrimitive() says:
Object
Return a default value for the Object. The default value of an object is retrieved by calling the [[DefaultValue]] internal method of the object, passing the optional hint PreferredType. The behaviour of the [[DefaultValue]] internal method is defined by this specification for all native ECMAScript objects in 8.12.8.
[[DefaultValue]] says:
8.12.8 [[DefaultValue]] (hint)
When the [[DefaultValue]] internal method of O is called with hint String, the following steps are taken:
Let toString be the result of calling the [[Get]] internal method of object O with argument "toString".
If IsCallable(toString) is true then,
a. Let str be the result of calling the [[Call]] internal method of toString, with O as the this value and an empty argument list.
b. If str is a primitive value, return str.
The .toString of an array says:
15.4.4.2 Array.prototype.toString ( )
When the toString method is called, the following steps are taken:
Let array be the result of calling ToObject on the this value.
Let func be the result of calling the [[Get]] internal method of array with argument "join".
If IsCallable(func) is false, then let func be the standard built-in method Object.prototype.toString (15.2.4.2).
Return the result of calling the [[Call]] internal method of func providing array as the this value and an empty arguments list.
So +[] comes down to +"", because [].join() === "".
Again, the + is defined as:
11.4.6 Unary + Operator
The unary + operator converts its operand to Number type.
The production UnaryExpression : + UnaryExpression is evaluated as follows:
Let expr be the result of evaluating UnaryExpression.
Return ToNumber(GetValue(expr)).
ToNumber is defined for "" as:
The MV of StringNumericLiteral ::: [empty] is 0.
So +"" === 0, and thus +[] === 0.
++[ [] ][+[]] === 1
+[] === 0
++[ [] ][0] === 1
[ +[] ] is [ 0 ]
Then we have a string concatenation:
1 + String([ 0 ]) === 10
The following is adapted from a blog post answering this question that I posted while this question was still closed. Links are to (an HTML copy of) the ECMAScript 3 spec, still the baseline for JavaScript in today's commonly used web browsers.
First, a comment: this kind of expression is never going to show up in any (sane) production environment and is only of any use as an exercise in just how well the reader knows the dirty edges of JavaScript. The general principle that JavaScript operators implicitly convert between types is useful, as are some of the common conversions, but much of the detail in this case is not.
The expression ++[[]][+[]]+[+[]] may initially look rather imposing and obscure, but is actually relatively easy break down into separate expressions. Below I’ve simply added parentheses for clarity; I can assure you they change nothing, but if you want to verify that then feel free to read up about the grouping operator. So, the expression can be more clearly written as
( ++[[]][+[]] ) + ( [+[]] )
Breaking this down, we can simplify by observing that +[] evaluates to 0. To satisfy yourself why this is true, check out the unary + operator and follow the slightly tortuous trail which ends up with ToPrimitive converting the empty array into an empty string, which is then finally converted to 0 by ToNumber. We can now substitute 0 for each instance of +[]:
( ++[[]][0] ) + [0]
Simpler already. As for ++[[]][0], that’s a combination of the prefix increment operator (++), an array literal defining an array with single element that is itself an empty array ([[]]) and a property accessor ([0]) called on the array defined by the array literal.
So, we can simplify [[]][0] to just [] and we have ++[], right? In fact, this is not the case because evaluating ++[] throws an error, which may initially seem confusing. However, a little thought about the nature of ++ makes this clear: it’s used to increment a variable (e.g. ++i) or an object property (e.g. ++obj.count). Not only does it evaluate to a value, it also stores that value somewhere. In the case of ++[], it has nowhere to put the new value (whatever it may be) because there is no reference to an object property or variable to update. In spec terms, this is covered by the internal PutValue operation, which is called by the prefix increment operator.
So then, what does ++[[]][0] do? Well, by similar logic as +[], the inner array is converted to 0 and this value is incremented by 1 to give us a final value of 1. The value of property 0 in the outer array is updated to 1 and the whole expression evaluates to 1.
This leaves us with
1 + [0]
... which is a simple use of the addition operator. Both operands are first converted to primitives and if either primitive value is a string, string concatenation is performed, otherwise numeric addition is performed. [0] converts to "0", so string concatenation is used, producing "10".
As a final aside, something that may not be immediately apparent is that overriding either one of the toString() or valueOf() methods of Array.prototype will change the result of the expression, because both are checked and used if present when converting an object into a primitive value. For example, the following
Array.prototype.toString = function() {
return "foo";
};
++[[]][+[]]+[+[]]
... produces "NaNfoo". Why this happens is left as an exercise for the reader...
Let’s make it simple:
++[[]][+[]]+[+[]] = "10"
var a = [[]][+[]];
var b = [+[]];
// so a == [] and b == [0]
++a;
// then a == 1 and b is still that array [0]
// when you sum the var a and an array, it will sum b as a string just like that:
1 + "0" = "10"
This one evaluates to the same but a bit smaller
+!![]+''+(+[])
[] - is an array is converted that is converted to 0 when you add or subtract from it, so hence +[] = 0
![] - evaluates to false, so hence !![] evaluates to true
+!![] - converts the true to a numeric value that evaluates to true, so in this case 1
+'' - appends an empty string to the expression causing the number to be converted to string
+[] - evaluates to 0
so is evaluates to
+(true) + '' + (0)
1 + '' + 0
"10"
So now you got that, try this one:
_=$=+[],++_+''+$
+[] evaluates to 0
[...] then summing (+ operation) it with anything converts array content to its string representation consisting of elements joined with comma.
Anything other like taking index of array (have grater priority than + operation) is ordinal and is nothing interesting.
Perhaps the shortest possible ways to evaluate an expression as "10" without digits are:
+!+[] + [+[]] // "10"
-~[] + [+[]] // "10"
Explanation
+!+[]:
+[] is evaluated as 0.
!0 is evaluated as true.
+true is evaluated as 1.
-~[] is the same as -(-1) which is evaluated as 1.
[+[]]:
+[] is evaluated as 0
[0] is an array with the single element 0.
Then, JS evaluates the 1 + [0], a Number + Array expression. Then the ECMA specification works: + operator converts both operands to a string by calling the ToPrimitive and ToString abstract operations. It operates as an additive function if both operands of an expression are numbers only. The trick is that arrays easily coerce their elements into a concatenated string representation.
Some examples:
1 + {} // "1[object Object]"
1 + [] // "1"
1 + new Date() // "1Wed Jun 19 2013 12:13:25 GMT+0400 (Caucasus Standard Time)"
[] + [] // ""
[1] + [2] // "12"
{} + {} // "[object Object][object Object]" ¹
{a:1} + {b:2} // "[object Object][object Object]" ¹
[1, {}] + [2, {}] // "1,[object Object]2,[object Object]"
¹: Note that each line is evaluated in an expression context. The first {…} is an object literal, not a block, as would be the case in a statement context. In a REPL, you may see {} + {} resulting in NaN, because most REPLs operate in a statement context; here, the first {} is a block, and the code is equivalent to {}; +{};, with the final expression statement (whose value becomes the result of the completion record) is NaN because the unary + coerces the object to a number.
++[[]][+[]]+[+[]]
^^^
|
v
++[[]][+[]]+[0]
^^^
|
v
++[[]][0]+[0]
^^^^^^^
|
v
++[]+[0]
^^^
|
v
++[]+"0"
^^^^
|
v
++0+"0"
^^^
|
v
1+"0"
^^^^^
|
v
"10"
The + operator coerces any non-number operand via .valueOf(). If that doesn't return a number then .toString() is invoked.
We can verify this simply with:
const x = [], y = [];
x.valueOf = () => (console.log('x.valueOf() has been called'), y.valueOf());
x.toString = () => (console.log('x.toString() has been called'), y.toString());
console.log(`+x -> ${+x}`);
So +[] is the same as coercing "" into a number which is 0.
If any operand is a string then + concatenates.
Step by steps of that, + turn value to a number and if you add to an empty array +[]...as it's empty and is equal to 0, it will
So from there, now look into your code, it's ++[[]][+[]]+[+[]]...
And there is plus between them ++[[]][+[]] + [+[]]
So these [+[]] will return [0] as they have an empty array which gets converted to 0 inside the other array...
So as imagine, the first value is a 2-dimensional array with one array inside... so [[]][+[]] will be equal to [[]][0] which will return []...
And at the end ++ convert it and increase it to 1...
So you can imagine, 1 + "0" will be "10"...
Unary plus given string converts to number
Increment operator given string converts and increments by 1
[] == ''. Empty String
+'' or +[] evaluates 0.
++[[]][+[]]+[+[]] = 10
++[''][0] + [0] : First part is gives zeroth element of the array which is empty string
1+0
10
This is valid and returns the string "10" in JavaScript (more examples here):
console.log(++[[]][+[]]+[+[]])
Why? What is happening here?
If we split it up, the mess is equal to:
++[[]][+[]]
+
[+[]]
In JavaScript, it is true that +[] === 0. + converts something into a number, and in this case it will come down to +"" or 0 (see specification details below).
Therefore, we can simplify it (++ has precendence over +):
++[[]][0]
+
[0]
Because [[]][0] means: get the first element from [[]], it is true that:
[[]][0] returns the inner array ([]). Due to references it's wrong to say [[]][0] === [], but let's call the inner array A to avoid the wrong notation.
++ before its operand means “increment by one and return the incremented result”. So ++[[]][0] is equivalent to Number(A) + 1 (or +A + 1).
Again, we can simplify the mess into something more legible. Let's substitute [] back for A:
(+[] + 1)
+
[0]
Before +[] can coerce the array into the number 0, it needs to be coerced into a string first, which is "", again. Finally, 1 is added, which results in 1.
(+[] + 1) === (+"" + 1)
(+"" + 1) === (0 + 1)
(0 + 1) === 1
Let's simplify it even more:
1
+
[0]
Also, this is true in JavaScript: [0] == "0", because it's joining an array with one element. Joining will concatenate the elements separated by ,. With one element, you can deduce that this logic will result in the first element itself.
In this case, + sees two operands: a number and an array. It’s now trying to coerce the two into the same type. First, the array is coerced into the string "0", next, the number is coerced into a string ("1"). Number + String === String.
"1" + "0" === "10" // Yay!
Specification details for +[]:
This is quite a maze, but to do +[], first it is being converted to a string because that's what + says:
11.4.6 Unary + Operator
The unary + operator converts its operand to Number type.
The production UnaryExpression : + UnaryExpression is evaluated as follows:
Let expr be the result of evaluating UnaryExpression.
Return ToNumber(GetValue(expr)).
ToNumber() says:
Object
Apply the following steps:
Let primValue be ToPrimitive(input argument, hint String).
Return ToString(primValue).
ToPrimitive() says:
Object
Return a default value for the Object. The default value of an object is retrieved by calling the [[DefaultValue]] internal method of the object, passing the optional hint PreferredType. The behaviour of the [[DefaultValue]] internal method is defined by this specification for all native ECMAScript objects in 8.12.8.
[[DefaultValue]] says:
8.12.8 [[DefaultValue]] (hint)
When the [[DefaultValue]] internal method of O is called with hint String, the following steps are taken:
Let toString be the result of calling the [[Get]] internal method of object O with argument "toString".
If IsCallable(toString) is true then,
a. Let str be the result of calling the [[Call]] internal method of toString, with O as the this value and an empty argument list.
b. If str is a primitive value, return str.
The .toString of an array says:
15.4.4.2 Array.prototype.toString ( )
When the toString method is called, the following steps are taken:
Let array be the result of calling ToObject on the this value.
Let func be the result of calling the [[Get]] internal method of array with argument "join".
If IsCallable(func) is false, then let func be the standard built-in method Object.prototype.toString (15.2.4.2).
Return the result of calling the [[Call]] internal method of func providing array as the this value and an empty arguments list.
So +[] comes down to +"", because [].join() === "".
Again, the + is defined as:
11.4.6 Unary + Operator
The unary + operator converts its operand to Number type.
The production UnaryExpression : + UnaryExpression is evaluated as follows:
Let expr be the result of evaluating UnaryExpression.
Return ToNumber(GetValue(expr)).
ToNumber is defined for "" as:
The MV of StringNumericLiteral ::: [empty] is 0.
So +"" === 0, and thus +[] === 0.
++[ [] ][+[]] === 1
+[] === 0
++[ [] ][0] === 1
[ +[] ] is [ 0 ]
Then we have a string concatenation:
1 + String([ 0 ]) === 10
The following is adapted from a blog post answering this question that I posted while this question was still closed. Links are to (an HTML copy of) the ECMAScript 3 spec, still the baseline for JavaScript in today's commonly used web browsers.
First, a comment: this kind of expression is never going to show up in any (sane) production environment and is only of any use as an exercise in just how well the reader knows the dirty edges of JavaScript. The general principle that JavaScript operators implicitly convert between types is useful, as are some of the common conversions, but much of the detail in this case is not.
The expression ++[[]][+[]]+[+[]] may initially look rather imposing and obscure, but is actually relatively easy break down into separate expressions. Below I’ve simply added parentheses for clarity; I can assure you they change nothing, but if you want to verify that then feel free to read up about the grouping operator. So, the expression can be more clearly written as
( ++[[]][+[]] ) + ( [+[]] )
Breaking this down, we can simplify by observing that +[] evaluates to 0. To satisfy yourself why this is true, check out the unary + operator and follow the slightly tortuous trail which ends up with ToPrimitive converting the empty array into an empty string, which is then finally converted to 0 by ToNumber. We can now substitute 0 for each instance of +[]:
( ++[[]][0] ) + [0]
Simpler already. As for ++[[]][0], that’s a combination of the prefix increment operator (++), an array literal defining an array with single element that is itself an empty array ([[]]) and a property accessor ([0]) called on the array defined by the array literal.
So, we can simplify [[]][0] to just [] and we have ++[], right? In fact, this is not the case because evaluating ++[] throws an error, which may initially seem confusing. However, a little thought about the nature of ++ makes this clear: it’s used to increment a variable (e.g. ++i) or an object property (e.g. ++obj.count). Not only does it evaluate to a value, it also stores that value somewhere. In the case of ++[], it has nowhere to put the new value (whatever it may be) because there is no reference to an object property or variable to update. In spec terms, this is covered by the internal PutValue operation, which is called by the prefix increment operator.
So then, what does ++[[]][0] do? Well, by similar logic as +[], the inner array is converted to 0 and this value is incremented by 1 to give us a final value of 1. The value of property 0 in the outer array is updated to 1 and the whole expression evaluates to 1.
This leaves us with
1 + [0]
... which is a simple use of the addition operator. Both operands are first converted to primitives and if either primitive value is a string, string concatenation is performed, otherwise numeric addition is performed. [0] converts to "0", so string concatenation is used, producing "10".
As a final aside, something that may not be immediately apparent is that overriding either one of the toString() or valueOf() methods of Array.prototype will change the result of the expression, because both are checked and used if present when converting an object into a primitive value. For example, the following
Array.prototype.toString = function() {
return "foo";
};
++[[]][+[]]+[+[]]
... produces "NaNfoo". Why this happens is left as an exercise for the reader...
Let’s make it simple:
++[[]][+[]]+[+[]] = "10"
var a = [[]][+[]];
var b = [+[]];
// so a == [] and b == [0]
++a;
// then a == 1 and b is still that array [0]
// when you sum the var a and an array, it will sum b as a string just like that:
1 + "0" = "10"
This one evaluates to the same but a bit smaller
+!![]+''+(+[])
[] - is an array is converted that is converted to 0 when you add or subtract from it, so hence +[] = 0
![] - evaluates to false, so hence !![] evaluates to true
+!![] - converts the true to a numeric value that evaluates to true, so in this case 1
+'' - appends an empty string to the expression causing the number to be converted to string
+[] - evaluates to 0
so is evaluates to
+(true) + '' + (0)
1 + '' + 0
"10"
So now you got that, try this one:
_=$=+[],++_+''+$
+[] evaluates to 0
[...] then summing (+ operation) it with anything converts array content to its string representation consisting of elements joined with comma.
Anything other like taking index of array (have grater priority than + operation) is ordinal and is nothing interesting.
Perhaps the shortest possible ways to evaluate an expression as "10" without digits are:
+!+[] + [+[]] // "10"
-~[] + [+[]] // "10"
Explanation
+!+[]:
+[] is evaluated as 0.
!0 is evaluated as true.
+true is evaluated as 1.
-~[] is the same as -(-1) which is evaluated as 1.
[+[]]:
+[] is evaluated as 0
[0] is an array with the single element 0.
Then, JS evaluates the 1 + [0], a Number + Array expression. Then the ECMA specification works: + operator converts both operands to a string by calling the ToPrimitive and ToString abstract operations. It operates as an additive function if both operands of an expression are numbers only. The trick is that arrays easily coerce their elements into a concatenated string representation.
Some examples:
1 + {} // "1[object Object]"
1 + [] // "1"
1 + new Date() // "1Wed Jun 19 2013 12:13:25 GMT+0400 (Caucasus Standard Time)"
[] + [] // ""
[1] + [2] // "12"
{} + {} // "[object Object][object Object]" ¹
{a:1} + {b:2} // "[object Object][object Object]" ¹
[1, {}] + [2, {}] // "1,[object Object]2,[object Object]"
¹: Note that each line is evaluated in an expression context. The first {…} is an object literal, not a block, as would be the case in a statement context. In a REPL, you may see {} + {} resulting in NaN, because most REPLs operate in a statement context; here, the first {} is a block, and the code is equivalent to {}; +{};, with the final expression statement (whose value becomes the result of the completion record) is NaN because the unary + coerces the object to a number.
++[[]][+[]]+[+[]]
^^^
|
v
++[[]][+[]]+[0]
^^^
|
v
++[[]][0]+[0]
^^^^^^^
|
v
++[]+[0]
^^^
|
v
++[]+"0"
^^^^
|
v
++0+"0"
^^^
|
v
1+"0"
^^^^^
|
v
"10"
The + operator coerces any non-number operand via .valueOf(). If that doesn't return a number then .toString() is invoked.
We can verify this simply with:
const x = [], y = [];
x.valueOf = () => (console.log('x.valueOf() has been called'), y.valueOf());
x.toString = () => (console.log('x.toString() has been called'), y.toString());
console.log(`+x -> ${+x}`);
So +[] is the same as coercing "" into a number which is 0.
If any operand is a string then + concatenates.
Step by steps of that, + turn value to a number and if you add to an empty array +[]...as it's empty and is equal to 0, it will
So from there, now look into your code, it's ++[[]][+[]]+[+[]]...
And there is plus between them ++[[]][+[]] + [+[]]
So these [+[]] will return [0] as they have an empty array which gets converted to 0 inside the other array...
So as imagine, the first value is a 2-dimensional array with one array inside... so [[]][+[]] will be equal to [[]][0] which will return []...
And at the end ++ convert it and increase it to 1...
So you can imagine, 1 + "0" will be "10"...
Unary plus given string converts to number
Increment operator given string converts and increments by 1
[] == ''. Empty String
+'' or +[] evaluates 0.
++[[]][+[]]+[+[]] = 10
++[''][0] + [0] : First part is gives zeroth element of the array which is empty string
1+0
10
As far as I know in JavaScript !! is supposed to normalize a boolean value converting it to true or false from some other type. This would mean that the "0" converts to boolean true. On the other hand if I compare it with false it turns out that it is in fact false (as the result of the comparison is true). What rule am I missing here. I have tested it in IE and Opera.
The == operator checks for loose equality, which has nothing to do with truthiness.
Specifically, it will convert to operands to numbers, then compare the numbers.
Strings containing numbers convert to the numbers that they contain; booleans convert to 0 and 1.
Objects are converted by calling valueOf, if defined.
Thus, all of the following are true:
"1" == 1
"0" == false
"1" == true
"2" != true
"2" != false
({ valueOf:function() { return 2; } }) == 2
({ valueOf:function() { return 1; } }) == true
In the first case, a non-empty string is equivalent to true.
In the second case, because one operand is a boolean, both operands are converted to numeric values. I believe false converts to the numeric value 0 and the string "0" also converts to a numeric 0, resulting in 0 == 0 which is true.
Check out the Mozilla reference for operator behavior.
For the first expression, section 9.2 of ECMA-262 defines an abstract operation ToBoolean internally used by the logical NOT operator. It says:
String
The result is false if the argument is the empty String (its length is zero); otherwise the result is true.
For the second expression, JavaScript will perform type coercion when it attempts to compare these values of different data types. Douglas Crockford says that this is a misfeature. It would be false if you had used === instead of ==. The rules are rather complex, so you should directly look in section 11.9.3 of ECMA-262 for the details.
I always thought that an if statement essentially compared it's argument similar to == true. However the following experiment in Firebug confirmed my worst fears—after writing Javascript for 15 years I still have no clue WTF is going on:
>>> " " == true
false
>>> if(" ") console.log("wtf")
wtf
My worldview is in shambles here. I could run some experiments to learn more, but even then I would be losing sleep for fear of browser quirks. Is this in a spec somewhere? Is it consistent cross-browser? Will I ever master javascript?
"If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers; if either operand is a string, the other one is converted to a string."
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Comparison_Operators
So the first one does:
Number(" ")==Number(true)
While the second one is evaluated like this:
if(Boolean(" ")==true) console.log("wtf")
I am guessing that it is the first part that is a problem, not the second.
It probably does some weird casting (most likely, true is cast to a string instead of " " being cast to a boolean value.
What does FireBug return for Boolean(" ") ?
JavaScript can be quirky with things like this. Note that JavaScript has == but also ===. I would have thought that
" " == true
would be true, but
" " === true
would be false. The === operator doesn't do conversions; it checks if the value and the type on both sides of the operator are the same. The == does convert 'truthy' values to true and 'falsy' values to false.
This might be the answer - from JavaScript Comparison Operators (Mozilla documentation):
Equal (==)
If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers; if either operand is a string, the other one is converted to a string
Highly recommended: Douglas Crockford on JavaScript.
Answer: aTruthyValue and true are not the same.
The semantic of the if statement is easy:
if(aTruthyValue) {
doThis
} else {
doThat
}
Now it's just the definition of what a truthy value is. A truthy value is, unfortunately, not something that is simply "== true" or "=== true".
ECMA-262 1.5
Setion 9.2 explains what values are truthy and which are not.
I recommend using === whenever possible, if only to avoid having existential crises.