Q:

Distance from point to line 3d formula

I am looking for a javascript 3D formula to get the distance from a point to the line. The formula can also be in another programming language.
P is a point, and A & B are points of the line.
P=(4,2,1);
A=(1,0,1);
B=(1,2,0);

A:

The closest point X to the point Pon the line (A, V) is that point, where the line (X, P) is normal to the line (A, B).
If a line is defined by two points A and B, then a Unit vector D which gives the direction of the line can be calcualted as follows (Note the length of a unit vector is 1):
D = normalize(B-A);

For the following formula a point O on the line is needed, e.g. O = A.
Now the closest point X to the point P on the line (O, D) has to be found.
First calculate a vector V from O to P:
V = P - O;

The distance d from O to the intersection point (closest point) X can be calculated by the Dot product.
In general The dot product of 2 vectors is equal the cosine of the angle between the 2 vectors multiplied by the magnitude (length) of both vectors.
dot( A, B ) == | A | * | B | * cos( angle_A_B ) 

Since D is a unit vector, the dot product of V and D is equal the cosine of the angle between the line (O, D) and the vector V, multiplied by the amount (length) of V:
d = dot(V, D);

The intersection point X, can be calculated by shifting the point O along the line (D) by the distance d:
X = O + D * d;    

So the formula for the intersection point is:
O ... any point on the line
D ... unit vector which points in the direction of the line
P ... the "Point"

X = O + D * dot(P-O, D); 

The calculation by points on the line A, B and the point P is:
D = normalize(B-A);
X = A + D * dot(P-A, D);

The dot Product for 3 dimensional cartesian coordinates can be expressed as:
dot(A, B) = Ax*Bx + Ay*By + Az*Bz

A normalized vector (unit vector) can be calculated by:
len(A) = sqrt(Ax*Ax + Ay*Ay + Az*Az)
notrmalize(A) = A / len(A)

In pure javascipt this can be clacualted as follows:
var P=[4,2,1];
var A=[1,0,1];
var B=[1,2,0];

var AB    = [B[0]-A[0], B[1]-A[1], B[2]-A[2]];
var lenAB = Math.sqrt(AB[0]*AB[0] + AB[1]*AB[1] + AB[2]*AB[2]);

var D  = [AB[0]/lenAB, AB[1]/lenAB, AB[2]/lenAB];
var AP = [P[0]-A[0], P[1]-A[1], P[2]-A[2]];

var d = D[0]*AP[0] + D[1]*AP[1] + D[2]*AP[2];

var X = [A[0] + d * D[0], A[1] + d * D[1], A[2] + d * D[2]];

It is easy to this by Three.js - Vector3, where the operations for the vector arithmetic like add, sub, dot and normalize are defined:
var P = new THREE.Vector3( 4, 2, 1 );
var A = new THREE.Vector3( 1, 0, 1 );
var B = new THREE.Vector3( 1, 2, 0 );

var D = B.clone().sub( A ).normalize();
var d = P.clone().sub( A ).dot( D );
var X = A.clone().add( D.clone().multiplyScalar( d ) ); 

