Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does [[]][0]++ work but []++ throws run-time exception?

Tags:

Why does the first line work while the second line throws run-time exception?

The first line:

[[]][0]++; //this line works fine 

The second line:

[]++; //this lines throws exception 
like image 653
Ervin Szilagyi Avatar asked Aug 26 '17 08:08

Ervin Szilagyi


People also ask

What causes runtime exception?

A runtime error can be caused by poor programming practices. If the engineer loads his software with memory leaks, it can cause a runtime error. If software patches are available, they can be installed to fix this problem.

Is Divide by zero a runtime exception?

Trying to divide an integer or Decimal number by zero throws a DivideByZeroException exception. To prevent the exception, ensure that the denominator in a division operation with integer or Decimal values is non-zero.

What causes runtime exception in Java?

This Java runtime exception happens when the wrong type of object is placed into an array. In the example below, a BigInteger array is created, followed by an attempt to add a Double.


1 Answers

[[]][0]++ 

is equivalent to

var tmp = [[]]; tmp[0] = tmp[0]+1; 

tmp[0] is an empty array, which is cast to the number 0, which increments to 1.

This only works because <array>[<index>]++ looks valid. It takes some type juggling, but it gets there.

But []++ is outright invalid. There's no way to make it make sense.

[] = []+1; 

The left-hand side here is indeed invalid. You can't assign to an empty array.

like image 189
Niet the Dark Absol Avatar answered Sep 27 '22 19:09

Niet the Dark Absol