JavaScript can do basic mathematical operations. It will also concatenate strings together to make a longer string.

Basic Math and JavaScript

Performing basic mathematical operations in JavaScript is fairly straight forward. You can use + for addition, - for subtraction, * for multiplication and / for division.

You may also include a variable name in the operation if it has a numerical value and is not a string or Boolean value.

Example of basic math:

total = 3 + 4;
total = 18 - 5;
total = 21 * 7;
total = 35 / 6;
total = 45 + currentAmt;

In each case in the example above, the variable total holds the value of the mathematical operation. The equal sign + is the assignment operator that assigns the value or the mathmatical operation to the variable of total

The Order of Mathematical Operations

If you have several mathematical operations in one line, you must recognize that there is a specific order for how the operations will be performed or you may get the wrong value.

This is the order of operations: any thing in parentheses, multiplication & division (left to right), addition & subtraction (left to right).

totalA = 4 + 6 * 7 - 24 / 6 * 24  // the total is -50
totalB = (4+6) * 7 - (24 / 6) * 24 // the total is -26 

Three dot cartouche

Concatenation in JavaScript

If you need to combine strings to make a longer string, you can use the plus sign + in a statement. You can also concatenate string variables together.

var allInfo = "John" + " " + "Smith";

var fName = "John";
var lName = "Smith";
var fullName = fName + " " + lName;

You can not remove strings with the minus sign, that takes other steps.

There are some special rules for combining strings with numbers, or variables that represent numbers, to make longer strings.