JavaScript Vector

Vectors are fundamental mathematical entities characterized by both their magnitude and direction. In the realm of mathematics, a vector represents a quantity that possesses both size and orientation, typically illustrated as an arrow on a coordinate plane. In computer science and programming, vectors are widely employed, especially in areas such as graphics rendering, physics simulations, and game design.

In JavaScript, vectors serve to represent various entities such as positions, velocities, forces, or directions within applications. Typically, these vectors are implemented using arrays or objects that hold components like x, y, and z coordinates. A solid understanding of vectors in JavaScript is crucial for activities such as modifying graphical elements on a web page, simulating physical interactions in gaming environments, or performing calculations involving changes in 3D graphics.

The capability of JavaScript to proficiently manage vectors renders it an essential tool for web developers and software engineers engaged in projects that require vector-oriented mathematical calculations.

Basics of Vectors

In the field of mathematics, a vector is defined as a geometric construct that represents both magnitude and direction. In contrast to scalar quantities, which are characterized solely by their magnitude, vectors incorporate both size and orientation. This duality is essential for accurately depicting concepts such as velocity, force, and displacement.

The key features of a vector consist of the following:

  • Magnitude measures the size of a vector and is usually denoted as |v| or "v".
  • Direction: Indicates the orientation of the vector, usually depicted with an arrow.
  • Basic vector operations are essential in both mathematics and computer science.
  • Adding Vectors: Combining multiple vectors to determine their total resultant vector. This is done by including matching parts of the vectors.
  • Example
    
    For example, if a = (a1, a2) and b = (b1, b2), then a + b = (a1 + b1, a2 + b2).
    
  • Vector Subtraction: In a manner akin to vector addition, vector subtraction entails the removal of corresponding segments from one vector based on another.
  • Example
    
    For example, a - b = (a1 - b1, a2 - b2).
    
  • Scalar Multiplication: A vector resulting from the multiplication of a scalar is referred to as a scaled vector by that particular number.
  • Example
    
    When v = (v1, v2), multiplying it by a scalar k results in kv = (k * v1, k * v2).
    

Vectors are generally represented mathematically through sequences or columns of numerical values. To illustrate this concept, consider how a two-dimensional vector v = (v1, v2) can be expressed as a column matrix [v1; v2], while a three-dimensional vector u = (u1, u2, u3) can be depicted as [u1; u2; u3].

Vectors are represented visually as arrows on a coordinate plane, originating from the point of origin and extending towards their terminal points. The magnitude of the vector is indicated by the length of the arrow, while the direction is conveyed by the orientation of the arrow in relation to the coordinate axes.

Vectors in JavaScript

In JavaScript, vectors can be effectively represented through the use of arrays or objects to illustrate their components. Arrays present a straightforward approach to storing a vector's elements, while objects deliver a more structured manner to define the characteristics of a vector.

Utilizing Arrays for Vector Representation

A widely utilized method for integrating vectors in JavaScript involves the use of arrays to hold vector components. For example, a two-dimensional vector can be depicted as an array containing two elements, corresponding to the x and y coordinates.

Example

// Representing a 2D vector using an array
let vector2D = [3, 4]; // Vector (3, 4)
In the same way, a 3D vector can be depicted using an array consisting of three elements.
// Representing a 3D vector using an array
let vector3D = [1, 2, -1]; // Vector (1, 2, -1)

Using Objects to Represent Vectors

In JavaScript, objects provide a structured approach to defining vectors by associating particular properties with their respective components. This technique can enhance both the clarity and maintainability of the code.

Example

// Representing a 2D vector using an object
let vector2D = {
    x: 3,
    y: 4
}; // Vector (3, 4)
// Representing a 3D vector using an object
let vector3D = {
    x: 1,
    y: 2,
    z: -1
}; // Vector (1, 2, -1)

Examples of code for manipulating vectors.

Once vectors are established via arrays or objects, they can be utilized for a variety of operations.

Example

// Addition of two 2D vectors
function adductors(v1, v2) {
    return [v1[0] + v2[0], v1[1] + v2[1]];
}
let vectorA = [3, 4];
let vectorB = [1, 2];
let result = adductors(vector, vector);
console.log("Result of vector addition:", result); // Output: [4, 6]
// Scalar multiplication of a 3D vector
function multiplyVectorByScalar(vector, scalar) {
    return [vector.x * scalar, vector.y * scalar, vector.z * scalar];
}
let vectors = { x: 1, y: 2, z: -1 };
let scalar = 2;
let scaled vector = multiplyVectorByScalar(vectors, scalar);
console.log("Scaled vector:", scaled vector); 
// Output: [2, 4, -2]

Vector Operations in JavaScript

Executing vector operations is crucial in JavaScript programming, especially when dealing with activities related to graphics, physics simulations, or mathematical computations.

Addition and subtraction of vectors

The operation of incorporating or removing equivalent components of vectors is referred to as vector addition and subtraction.

Example of addition

Example

function addVectors(v1, v2) {
    return [v1[0] + v2[0], v1[1] + v2[1], v1[2] + v2[2]]; // Assuming 3D vectors
}
let vectorA = [3, 4, 1];
let vectorB = [1, 2, 2];
let resultAddition = addVectors(vector, vector);
console.log("Result of vector addition:", resultAddition); 
// Output: [4, 6, 3]

Example of subtraction

Example

function subtractVectors(v1, v2) {
    return [v1[0] - v2[0], v1[1] - v2[1], v1[2] - v2[2]]; // Assuming 3D vectors
}
let resultSubtraction = subtractVectors(vector, vector);
console.log("Result of vector subtraction:", resultSubtraction); // Output: [2, 2, -1]

Multiplying a scalar by a vector

Scalar multiplication refers to the operation of multiplying a scalar quantity by every element of a vector.

Scalar product

The scalar result is obtained from the dot product of two vectors.

Example of Scalar Multiplication:

Example

function multiplyVectorByScalar(vector, scalar) {
    return [vector[0] * scalar, vector[1] * scalar, vector[2] * scalar]; // Assuming 3D vector
}
let scalar = 2;
let scaledVector = multiplyVectorByScalar(vector, scalar);
console.log("Scaled vector:", scaledVector); // Output: [6, 8, 2]

Scalar multiplication is frequently utilized to adjust the dimensions of vectors in graphical applications or in simulations within physics.

Dot Product

The dot product, also known as the scalar product, of two vectors yields a scalar quantity.

Example of Dot Product:

Example

function dotProduct(v1, v2) {
    let result = 0;
    for (let i = 0; i < v1.length; i++) {
        result += v1[i] * v2[i];
    }
    return result;
}
let vectorC = [1, 2, 3];
let vectorD = [4, 5, 6];
let resultDotProduct = dotProduct(vectorC, vectorD);
console.log("Dot product of vectors:", resultDotProduct); // Output: 32

The dot product serves as a valuable tool for determining the angle between vectors, computing projections, or addressing geometric problems.

Cross Product

The vector product, also referred to as the cross product, of two vectors results in a new vector that is orthogonal to both of the initial vectors.

Example of Cross Product

Example

function crossProduct(v1, v2) {
    return [
        v1[1] * v2[2] - v1[2] * v2[1],
        v1[2] * v2[0] - v1[0] * v2[2],
        v1[0] * v2[1] - v1[1] * v2[0]
    ];
}
let vectorE = [2, 3, 4];
let vectorF = [5, 6, 7];
let resultCrossProduct = crossProduct(vectorE, vectorF);
console.log("Cross product of vectors:", resultCrossProduct); // Output: [-3, 6, -3]

The cross-product plays a vital role in three-dimensional graphics by calculating surface normals, determining orientation, and addressing various vector-related problems.

Applications of Vectors in JavaScript

Vectors play a crucial role in JavaScript development and are widely applied in various fields such as physics simulations, game creation, and graphical representations. Here are several examples that illustrate the significance of vectors in JavaScript.

Simulating physical phenomena using physics principles

In physics simulations, vectors are utilized to represent various elements such as forces, velocities, and the positions of objects. In scenarios like projectile motion and collision events, vectors serve to define both the magnitude and direction of the forces that influence the behavior of the objects involved.

Here is a straightforward illustration of how to displace an object by utilizing a force vector:

Example

let position = { x: 0, y: 0 };
let velocity = { x: 2, y: 4 }; // Velocity vector (2, 4) units per second
function applyForce(force) {
    // Update position based on velocity (time-based calculation)
    position.x += velocity.x * force;
    position.y += velocity.y * force;
}
// Simulate applying a force over time
applyForce(3); // Applying force for 3 seconds
console.log("Final position:", position); // Output: { x: 6, y: 12 }

Game Development

Vectors are fundamental in the realm of game development, serving as vital components for denoting the positions, velocities, orientations, and various characteristics of objects. They enable smooth movement, enable collision detection, and allow for the execution of physics interactions within gaming environments.

Below is an illustration showcasing movement that relies on vectors:

Example

let playerPosition = { x: 100, y: 100 };
let playerVelocity = { x: 0, y: 0 };
// Update player position based on velocity
function updatePlayerPosition() {
    playerPosition.x += playerVelocity.x;
    playerPosition.y += playerVelocity.y;
}
// Example usage: Move the player upwards
playerVelocity.y = -5; // Set upward velocity
updatePlayerPosition(); // Update player position
console.log("New player position:", playerPosition); // Output: { x: 100, y: 95 }

Graphics

Vectors play a crucial role in graphics programming as they facilitate geometric transformations such as translation, rotation, scaling, and projection. They are utilized to represent points, lines, shapes, and transformations in both two-dimensional and three-dimensional spaces. Below is a straightforward illustration of scaling through the use of vectors.

Example

let point = { x: 2, y: 3 };
// Scale the point using a scalar factor
function scale point(point, scaleFactor) {
    point.x *= scaleFactor;
    point.y *= scaleFactor;
}
// Example usage: Scale the point by a factor of 2
scalePoint(point, 2);
console.log("Scaled point:", point); // Output: { x: 4, y: 6 }

Conclusion

In conclusion, vectors play a crucial role in JavaScript programming, serving as a fundamental component for executing complex mathematical computations, visual modifications, and real-world modeling. The versatility of vectors enables developers to easily represent and manipulate various entities such as positions, velocities, forces, and directions.

Understanding vector principles empowers developers to create engaging and interactive applications, including games, simulations, animations, and graphical user interfaces. By leveraging vector operations, developers can achieve smooth animations, accurate physics simulations, and efficient geometric transformations.

Input Required

This code uses input(). Please provide values below: