Skip to main content

How to Multiply in JavaScript

How to Multiply in JavaScript

Multiplication is one of the basic arithmetic operations you can perform in JavaScript. This guide will show you how to multiply numbers, arrays, and even objects using JavaScript's built-in operators and functions.


Multiplying Numbers

In JavaScript, you can multiply numbers using the * operator. Here's how it works:

const result = 5 * 3;
console.log(result); // Output: 15

In this example:

  • 5 * 3 multiplies the numbers 5 and 3.
  • The result, 15, is stored in the result variable and logged to the console.

Multiplying Variables

You can also multiply variables that store numeric values:

const num1 = 7;
const num2 = 4;
const product = num1 * num2;
console.log(product); // Output: 28

Here, num1 and num2 are multiplied, and the product is stored in the product variable.


Multiplying Elements in an Array

If you want to multiply all the elements in an array, you can use the reduce() method:

const numbers = [2, 3, 4];
const product = numbers.reduce((accumulator, currentValue) => accumulator * currentValue, 1);
console.log(product); // Output: 24

In this example:

  • The reduce() method multiplies each element of the numbers array.
  • The accumulator is initialized to 1 and updated with each multiplication.
  • The final product, 24, is stored in the product variable.

Multiplying Properties in an Object

To multiply numeric properties of an object, you can iterate over its keys and accumulate the product:

const dimensions = {
    length: 5,
    width: 10,
    height: 2
};

let volume = 1;
for (let key in dimensions) {
    if (dimensions.hasOwnProperty(key)) {
        volume *= dimensions[key];
    }
}

console.log(volume); // Output: 100

In this example:

  • We iterate over each property of the dimensions object.
  • The volume variable is updated with the product of the property values.
  • The final product, 100, represents the volume.

Conclusion

Multiplication in JavaScript can be performed using the * operator for numbers and variables. You can also use array methods like reduce() to multiply elements and loop through objects to multiply properties. These techniques allow you to perform various multiplication operations effectively in your JavaScript programs.

Comments