Logo
/
Programming
/
JavaScript Course
/

Commutative operation

JavaScript: Commutative operation

The phrase "changing the order of the addends does not change the sum" is familiar to everyone from school. This principle is called the commutative law and is one of the fundamental laws of arithmetic.

What is commutativity

An operation is called commutative if the order of the operands does not affect the result: if you swap the values, you get the same answer. An example of a commutative operation is addition.

console.log(3 + 2); // => 5
console.log(2 + 3); // => 5

The identical result confirms that the operation is commutative.

2 + 3 = 5     3 + 2 = 5
└──────────┬─────────┘
      same result

2 - 3 = -1    3 - 2 = 1
└──────────┬─────────┘
     different result

Non-commutative operations

But not all operations have this property. For example, subtraction is a non-commutative operation:

console.log(2 - 3); // => -1
console.log(3 - 2); // => 1

Swapping the operands gives a different result.

In programming, it works the same way

Commutativity in programming works exactly as it does in arithmetic. JavaScript strictly follows mathematical rules.

Other non-commutative operations:

  • Division: 8 / 2 ≠ 2 / 8
  • Exponentiation: 2 **3 ≠ 3** 2

Examples in code:

// Division
console.log(8 / 2);  // 8 divided by 2 = 4

// Exponentiation
console.log(3 ** 2); // 3 squared = 9

Therefore:

  • Always carefully check the order of the operands, especially when working with unfamiliar operations;
  • check commutativity experimentally rather than assuming it in advance.

Instructions

Write a program that solves two tasks and prints the answers to the screen — each on its own line.

  1. A painter wants to paint 8 sections of a fence, each in one of 2 colors. How many unique color combinations are there? Use the exponentiation operator **.
  2. You and two friends (3 people in total) bought 9 pastries and want to share them equally. How many does each person get? Use the division operator /.

Tips

If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:

  • Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Found a bug? Have something to add? Pull requests are welcome!