Get point projection on line defined by two points

How can I get a point projection on a line in the two following cases:

enter image description here

I have A, B, and P points defined by the x and y values in the 2D coordinating system. How can I get P’ point coordinates using javascript?
Every point is defined by the following values:

{
   x: number;
   y: number;
}