How does a color buffer and a vertex buffer fit together?

I’ve been looking at a couple of webgl tutorials but have some problem understanding the buffers.

In this tutorial a triangle and a square are drawn in color:

If I take the triangle in the above tutorial as an example it has two buffers:

  var triangleVertexPositionBuffer;
  var triangleVertexColorBuffer;

Ok, and then the buffers are created as follows:

triangleVertexPositionBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);
    var vertices = [
         0.0,  1.0,  0.0,
        -1.0, -1.0,  0.0,
         1.0, -1.0,  0.0
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
    triangleVertexPositionBuffer.itemSize = 3;
    triangleVertexPositionBuffer.numItems = 3;

    triangleVertexColorBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexColorBuffer);
    var colors = [
        1.0, 0.0, 0.0, 1.0,
        0.0, 1.0, 0.0, 1.0,
        0.0, 0.0, 1.0, 1.0,
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
    triangleVertexColorBuffer.itemSize = 4;
    triangleVertexColorBuffer.numItems = 3;

So, we create a buffer with the triangles vertices and we buffer that data - thats all fine. BUT when the color buffer is created, how does WebGL know that the colors we specify should act on each vertex that we specified in the position buffer? I don’t understand why the triangles vertices gets those colors and not just as easily the colors that we specify for the square?

Thanks for help!

When you draw the object, you use gl.bindBuffer/gl.vertexAttribPointer/gl.enableVertexAttribArray to bind those arrays to the rendering context before you call gl.drawElements to draw them.