The story about the elves is not far from true. Their role is performed by a rotation sensor. The rotation sensor is built in every EV3 or NXT motor. Thanks to that sensor the motor knows how many degrees it has rotated. But how does that happen?
How does the rotation sensor work?
To understand how the rotation sensor works, we should first disassemble the motor. It is not advisable you to do that which is why we have done it for you. You can see where the “magic” comes from:

The electric motor inside the motor uses a gear to rotate a special gear wheel:

As you can see, this gear wheel has a lot of holes:
Moreover, the motor is also equipped with a photocell:

When the gear wheel rotates, the photocell detects each hole. How does it work? With every rotation there is light going through each hole which the photocell detects. Between two consecutive holes, the gear wheel is opaque, so no light passes through it.
Each hole corresponds to a half degree of a motor rotation. Therefore, if the photocell counts 300 holes, the motor has rotated 150 degrees.