Commutative operation

Updated: 04/26/2017 by Computer Hope

commutative operationIn math, an operation is commutative if the order of the numbers used can be altered with the result remaining the same. For example, addition and multiplication are commutative operations, as shown below.

2+3 = 5
3+2 = 5
2*3 = 6
3*2 = 6

In contrast, subtraction and division are not commutative, since changing the order of the numbers involved will change the result of the calculation, as shown below.

2-7 = -5
7-2 = 5
3/4 = 0.75
4/3 = 1.3333333

In programming, this can be used with the logical AND or the logical OR operations to "short circuit" if a particular condition is met, so that other possibilities need not be tested. For example, with the AND operation, if the first condition is false, then the whole comparison must return false, so the remaining conditions are not evaluated. For example, a null value in JavaScript would create an error if it is used. A logical statement could be used to indicate if a value is null, then the remainder of the statement is not executed.

var x = 0;
if ( (y !== null) && (y > 0) && (y < 3) ) {
window.alert(y * 4);
}

In this case, if y is null, then the remainder of the statement is not executed. That prevents any errors with a null y variable and keeps additional processing from being done if y is null.

Programming terms